ChangeNotifierProvider(
builder: (context) => AppStateModel()..loadBrands(),
child: MyTestApp(),
)
Why we have to call like this AppStateModel()..loadBrands()
, how is cascading helping us here?
ChangeNotifierProvider(
builder: (context) => AppStateModel()..loadBrands(),
child: MyTestApp(),
)
Why we have to call like this AppStateModel()..loadBrands()
, how is cascading helping us here?
The builder
(now called create
) of ChangeNotifierProvider
needs to return an instance of the change notifier class, which in this case is AppStateModel
. Normally you would do that like this:
create: (context) => AppStateModel(),
However, sometimes you also want to run some method when you first create the class, in this case the loadBrands
method. If you tried to do this with a single dot like this:
create: (context) => AppStateModel().loadBrands(),
It would indeed call the loadBrands
method, but it would also give the ChangeNotifierProvider
the return value of the loadBrands
method, which is probably void
or Future<void>
, not what the ChangeNotifierProvider
needs.
Using the ..
double dot operator, on the other hand, returns the AppStateModel
itself while still calling the loadBrands
method in addition to that:
create: (context) => AppStateModel()..loadBrands(),
This is equivalent:
create: (context) {
final model = AppStateModel();
model.loadBrands();
return model;
},
I sometimes find the ..
operator hard to read. Just use the form that makes sense to you.
Cascade notation (..)
Cascades (..) allow you to make a sequence of operations on the same object. In addition to function calls, you can also access fields on that same object. This often saves you the step of creating a temporary variable and allows you to write more fluid code.
For example in your case, you can use Cascade operator
like:
//call the method of app state class without creating a variable to hold an instance of the class
AppStateModel()..loadBrands();
Instead of creating a variable like :
//create an object of appstate and store in a variable
AppStateModel appState;
//access the methods of appstate class
appSate.localBrands();
To read more on Cascade Operator
, check the link below:
Cascade Operators
I hope this helps.