如何使用 Provider 包初始化状态?

How to initialize state using the Provider package?

TL;DR - Getting providerInfo = null from Consumer<ProviderInfo>(
    builder: (context, providerInfo, child),

我有一个使用 scoped_model that works just fine but I want to refactor it so it'll use Provider

的 flutter 应用

带scoped_model的代码:

//imports...
void main() {
  runApp(MyApp());
}
class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  final MainModel _model = MainModel();// The data class, extends scoped_model.Model class, with all of other models...
  bool _isAuthenticated = false;
  @override
  void initState() {
    _model.init();
    super.initState();
}
@override
  Widget build(BuildContext context) {
    return ScopedModel<MainModel>(
      model: _model,
      child: MaterialApp(
        title: "MyApp",
        routes: {
          '/': (BuildContext context) => _isAuthenticated == false ? AuthenticationPage() : HomePage(_model),
          '/admin': (BuildContext context) =>
              _isAuthenticated == false ? AuthenticationPage() : AdminPage(_model),
        },
// the rest of build...

}

以及我尝试重构以使用 Provider 的代码:

//@lib/main.dart
//imports...
void main() {
  runApp(MyApp());
}
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<ProviderInfo>(
      builder: (context) {
        ProviderInfo(); // the data model. 
      },
      child: Consumer<ProviderInfo>(
        builder: (context, providerInfo, child) => MaterialApp(
              title: "MyApp",
              routes: {
                '/': (BuildContext context) {
                  providerInfo.isAuthenticated == false ? AuthenticationPage() : HomePage(providerInfo);
                },
                '/admin': (BuildContext context) {
                    providerInfo.isAuthenticated == false ? AuthenticationPage() : AdminPage(_model);
                },     
//the rest of build...
              },

//@ProviderInfo
class ProviderInfo extends CombinedModel with ProductModel, UserModel, UtilityModel {

  ProviderInfo() {
    this.init();
  }
}


此代码的问题在于,在 Consumer<ProviderInfo> 的构建器函数中,providerInfo 为空(当然,在路由等之后)。

我做错了什么? 我该如何重构它才能正常工作?

您忘记 return 您的提供者 builder 中的某些内容。

改变

 ProviderInfo() 

 return ProviderInfo()