InitState中的提供程序引发错误。 Provider.of< SomeProvider>(上下文) [英] Provider Throw Errors in InitState. Provider.of<SomeProvider>(context)

查看:184
本文介绍了InitState中的提供程序引发错误。 Provider.of< SomeProvider>(上下文)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在initState中访问提供者的上下文



我不断收到错误消息

  flutter:在构建Builder时引发了以下断言:
flutter:在
flutter之前调用了InheritedFromWidgetOfExactType(_Provider< ProductProvider>)或InheritedFromElement():完成。

每当我运行下面的代码

  if(Provider.of< ProductProvider>(上下文).selectedProduct == null){
product = Product();
product.isReturnable = true;
product.isActive = true;
product.premiumType =未选择;
product.category =未选择;
product.principal =未选择;
}否则{
产品= Provider.of< ProductProvider>(上下文).selectedProduct;
}

当我使用作用域模型时,上面的代码运行完美,但是,提供者模型和程序包的用户抛出异常。

解决方案

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


How do I access the context for the Provider in the initState

I keep getting the error

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

Whenever I run the code below

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;
    }

N.B. the above code worked perfectly when I used the Scoped Model, however, user the Provider Model and Package throws an exception.

What I need it to access the provider before the build process, because contents of the provider are needed to build the UI.

解决方案

Provider.of<ProductProvider>(context, listen: false).selectedProduct and ensure there are no NotifyListeners in the initState call.

这篇关于InitState中的提供程序引发错误。 Provider.of&lt; SomeProvider&gt;(上下文)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆