0
ChangeNotifierProvider(
  builder: (context) => AppStateModel()..loadBrands(),
  child: MyTestApp(),
)

Why we have to call like this AppStateModel()..loadBrands(), how is cascading helping us here?

Ankit
  • 11
  • 1

2 Answers2

5

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.

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
4

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.

void
  • 12,787
  • 3
  • 28
  • 42
  • The explanation here that you can call the method without creating a variable to hold an instance of the class begs the question of why you would want to create a variable, and this answer never explains that reason. The better answer is from Suragch who explains that the cascade is valuable not just to send an additional message, but to return something other than the usual return value from the method. – James Foster Sep 28 '21 at 20:51