1

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.

CodeMemory
  • 839
  • 7
  • 10

3 Answers3

4

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

CodeMemory
  • 839
  • 7
  • 10
  • Thanks for sharing! Isn't it a bit weird that you need to set `listen: false` even though it isn't a ListenableProvider? I mean what would it be listening to when not set to false? – Jonas Jun 22 '19 at 21:17
  • @Jonas the current widget listens by default. When `NotifyListeners()` is called, the widget will rebuild if `listen` is not set to `false` – Boy Sep 30 '19 at 10:56
1

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

siega
  • 2,508
  • 1
  • 19
  • 22
  • Hi siega, that would work but that too has some issues. The solution is:`Provider.of(context, listen: false).selectedProduct` and ensure there are no NotifyListeners in the initState call. – CodeMemory May 16 '19 at 14:17
1

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

Boy
  • 7,010
  • 4
  • 54
  • 68