as my understand, one of Provider benefits is to avoid rebuild the widget tree, by calling build function, but when i try it practically with this simple example:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:providerexamplelast/counterWidget.dart';
void main() => runApp(ChangeNotifierProvider<Provider1>(
create: (_) => Provider1(),
child: MaterialApp(
home: Counter(),
),
));
int n =0;
class Counter extends StatelessWidget {
@override
Widget build(BuildContext context) {
print("${n++}");
var counter = Provider.of<Provider1>(context);
return Scaffold(
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: ()=> counter.counter(),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("1"),
SizedBox(height: 5,),
countText(),
SizedBox(height: 5,),
Text("3"),
SizedBox(height: 5,),
Text("4"),
],
),
),
);
}
}
Widget countText(){
return Builder(
builder: (context){
var count = Provider.of<Provider1>(context);
return Text("${count.c}");
},
);
}
by using this part :
print("${n++}");
i noticed that (build) function is recall whenever i press the button and call (counter) function from provider?
so the question here it is just (Stateless) widget, how it rebuild again? and then why i need to use Provider if it is not solve this problem?
Edit: I heard about this way:
var counter = Provider.of<Provider1>(context, listen: false);
so is it solve this problem? and how?
var counter = Provider.of<Provider1>(context, listen: false);
The Provider
is one of state management mechanism which flutter have, under the hood, Provider keeps track of the changes which are done inside the widget. It doesn't matter to Provider
whether it's a Stateless
widget or Stateful
widget, It's gonna rebuild widget if anything gets change.
listen: false
tells the Provider
not to rebuild widget even if data gets modified.