在 ChangeNotifierProvider 中使用双点 (..) 运算符/级联

0 cascading dart flutter flutter-change-notifier

ChangeNotifierProvider(
  builder: (context) => AppStateModel()..loadBrands(),
  child: MyTestApp(),
)
Run Code Online (Sandbox Code Playgroud)

为什么我们必须这样调用AppStateModel()..loadBrands(),级联在这里如何帮助我们?

Sur*_*gch 6

builder(现在称为createChangeNotifierProvider需要返回更改通知程序类的实例,在本例中为AppStateModel。通常你会这样做:

create: (context) => AppStateModel(),
Run Code Online (Sandbox Code Playgroud)

但是,有时您还想在首次创建类时运行某些方法,在本例中是loadBrands方法。如果您尝试使用像这样的单个点来执行此操作:

create: (context) => AppStateModel().loadBrands(),
Run Code Online (Sandbox Code Playgroud)

它确实会调用该loadBrands方法,但它也会给出ChangeNotifierProvider该方法的返回值loadBrands,这可能是voidFuture<void>,而不是所ChangeNotifierProvider需要的。

..另一方面,使用双点运算符会返回AppStateModel自身,同时仍然调用loadBrands该方法:

create: (context) => AppStateModel()..loadBrands(),
Run Code Online (Sandbox Code Playgroud)

这是等价的:

create: (context) {
  final model = AppStateModel();
  model.loadBrands();
  return model;
},
Run Code Online (Sandbox Code Playgroud)

我有时发现..操作符很难读。只需使用对您有意义的形式即可。