1

How can I set a provider in the initState method? Tried doing listen: false but got an error:

final MyProvider myProvider = Provider.of<MyProvider>(context, listen: false);
if (myProvider.someVar == null) {
    myProvider.setSomeVar('yo');
}

I get the following error:

setState() or markNeedsBuild() called during build

Here's the providers method

void setSomeVar(String text) {
    someVar = text;
    notifyListeners();
  }
Jessica
  • 9,379
  • 14
  • 65
  • 136

1 Answers1

1

In your Provider, setSomeVar() is calling notifyListeners(). This is a no-no in initState and build(). Try using a addPostFrameCallback to setSomeVar() after the build is complete.

Also, when using addPostFrameCallback, for something that uses context, you should check for context == null as a precaution.

initState() {
  WidgetsBinding.instance.addPostFrameCallback((_) {
    if (context == null) return;
    log('Navigating to SplashPage');
    Navigator.pushReplacementNamed(context, splashRoute);
  });
  
  super.initState();
}
JonnyH
  • 358
  • 2
  • 8