flutterdartprovider

Flutter calling an init function for provider on creation


I want to have a global provider which I create in a MultiProvider-Widget on the top of my app like this:

 ChangeNotifierProvider(
          create: (context) => ThemeProvider()
            ..init(
              context: context,
              initialThemeMode: widget.themeMode,
            ),
        ),

As you can see I am also calling ..init(, to set the initial data. However that init is not actually called when opening the app. It is only called after I make the first call with this provider, e.g. setting a color with it like this:

  Container(
    height: 50,
    color: Provider.of<ThemeProvider>(context).color,
  ),

Is that expected behavior?


Solution

  • It is only called after I make the first call with this provider ... Is that expected behavior?

    Yes, see documentation for provider:

    NOTE:

    When using the create/update callback of a provider, it is worth noting that this callback is called lazily by default.

    This means that until the value is requested at least once, the create/update callbacks won't be called.

    This behavior can be disabled if you want to pre-compute some logic, using the lazy parameter:

    MyProvider(
      create: (_) => Something(),
      lazy: false,
    )