【问题标题】:Provider Throw Errors in InitState. Provider.of<SomeProvider>(context)InitState 中的提供程序引发错误。 Provider.of<SomeProvider>(上下文)
【发布时间】:2019-09-30 00:20:35
【问题描述】:

如何在 initState 中访问 Provider 的上下文

我不断收到错误

flutter: The following assertion was thrown building Builder:
flutter: inheritFromWidgetOfExactType(_Provider<ProductProvider>) or inheritFromElement() was called before
flutter: _ProductDetailsPageState.initState() completed.

每当我运行下面的代码时

if (Provider.of<ProductProvider>(context).selectedProduct == null) {
      product = Product();
      product.isReturnable = true;
      product.isActive = true;
      product.premiumType = "None Selected";
      product.category = 'None Selected';
      product.principal = 'None Selected';
    } else {
      product = Provider.of<ProductProvider>(context).selectedProduct;
    }

注意当我使用 Scoped Model 时,上面的代码运行良好,但是,用户 Provider Model 和 Package 会引发异常。

在构建过程之前我需要它来访问提供程序,因为构建 UI 需要提供程序的内容。

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

    使用Simon的AfterLayouthttps://pub.dev/packages/after_layout,在需要实现的函数中调用。它将在Build() 运行后调用

    【讨论】:

      【解决方案2】:

      Provider.of&lt;ProductProvider&gt;(context, listen: false).selectedProduct 并确保 initState 调用中没有 NotifyListeners。

      【讨论】:

      • 感谢分享!即使listen: false 不是ListenableProvider,你也需要设置它是不是有点奇怪?我的意思是当不设置为 false 时它会听什么?
      • @Jonas 当前小部件默认监听。调用NotifyListeners() 时,如果listen 未设置为false,则小部件将重建
      【解决方案3】:

      尝试使用Future.delayed(...) 推迟此通话

      【讨论】:

      • 嗨,siega,这可行,但也有一些问题。解决方案是:Provider.of&lt;ProductProvider&gt;(context, listen: false).selectedProduct 并确保 initState 调用中没有 NotifyListeners。
      猜你喜欢
      • 2019-12-24
      • 1970-01-01
      • 1970-01-01
      • 2021-11-03
      • 2020-12-26
      • 2021-01-19
      • 1970-01-01
      • 2021-11-13
      • 2014-07-08
      相关资源
      最近更新 更多