CodeMemory
CodeMemory

Reputation: 849

Provider Throw Errors in InitState. Provider.of<SomeProvider>(context)

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.

Upvotes: 1

Views: 2582

Answers (3)

Boy
Boy

Reputation: 7487

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

Upvotes: 1

CodeMemory
CodeMemory

Reputation: 849

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

Upvotes: 4

siega
siega

Reputation: 2868

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

Upvotes: 1

Related Questions