繁体   English   中英

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

[英]How to initialize state using the Provider package?

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

我有一个颤动的应用程序使用scoped_model工作得很好,但我想重构它所以它将使用提供程序

带有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为null(当然也在路由等之后)。

我做错了什么? 我怎么能重构它所以它会工作正常?

您忘记在提供商的builder中返回某些内容。

更改

 ProviderInfo() 

 return ProviderInfo() 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM