Provider Throw Errors in InitState. Provider.of

2020-05-08 07:50发布

问题:

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.

回答1:

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



回答2:

Try to postpone this call with Future.delayed(...)



回答3:

Use Simon's AfterLayout package https://pub.dev/packages/after_layout and call it in the function you need to implement. It will be called after Build() has been run



标签: dart flutter