【问题标题】:Why the constructor of class isn't executed when using provider in flutter?为什么在flutter中使用provider时不执行类的构造函数?
【发布时间】:2020-06-05 19:44:15
【问题描述】:
void main() {
  MainStream.init();
  runApp(
      MultiProvider(
          providers: [
            Provider(
              create: (context) => Test(context),
            ),
          ],
          child: MyApp()));
}

class Test {
  Test(BuildContext context) {
    print("Test");
  }
}

在此测试代码中,我希望在我的应用程序启动时打印出“测试”,但事实并非如此。我做错了什么?我看到了这样初始化提供程序的示例。

【问题讨论】:

  • 你确定create被调用了吗?

标签: flutter dart flutter-provider


【解决方案1】:

根据提供者文档,创建回调是延迟加载的,因此这是预期行为。如果您传递“lazy: false”,它应该可以按预期工作:

Provider(
    create: (context) => Test(context),
    lazy: false
),

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-08
    • 1970-01-01
    • 1970-01-01
    • 2020-03-06
    • 2014-04-22
    • 1970-01-01
    • 1970-01-01
    • 2020-06-03
    相关资源
    最近更新 更多