flutterthemes

how to set the theme for a Flutter app taking the primary color from a Provider store


I have the following code in Flutter:

void main() {
  runApp(
    ChangeNotifierProvider(
      create: (context) => MyStore(),
      child: MaterialApp(
        theme: primaryTheme(Provider.of<MyStore>(context).appColors.primaryColor),
        home: NavigationBarApp()
      ),
    )
  );
}

The store MyStore contains the primary color to use as the seed for the theme so it can be changed at any time by the user, but I get an error because the context is not in scope the way I'm attempting to use it.

how can I take the content of the context in this scope?


Solution

  • Wrap your MaterialApp with a builder like this:

    void main() {
      runApp(
        ChangeNotifierProvider(
          create: (context) => MyStore(),
          child: Builder(
          builder: (context)=> MaterialApp(
            theme: primaryTheme(Provider.of<MyStore>(context).appColors.primaryColor),
            home: NavigationBarApp()
          ),),
        )
      );
    }