简体   繁体   中英

How to i use the context built in Flutter MultiProvider, inside its child?

I am trying to use the MyTheme provider to set the theme value in MaterialApp, by using MultiProvider. However the MaterialApp is unable to access the MyTheme provider.

I am trying to change the theme by using a button inside the app, which will update the provider and in turn change the theme for the whole app.

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (context) => Result(),
        ),
        ChangeNotifierProvider(
          create: (context) => MyTheme(),
        ),
      ],
      child: MaterialApp(
        home: TasksScreen(),
        theme: ThemeData.light(),
        darkTheme: ThemeData.dark(),
        themeMode: context.watch<MyTheme>().currentTheme(),
      ),
    );
  }
}

I believe I am unable to access it because the consumer and provider is on the same level, but I am not sure how to go about it.

class MyTheme with ChangeNotifier {
  static bool _isDark = true;

  ThemeMode currentTheme() {
    return _isDark ? ThemeMode.dark : ThemeMode.light;
  }

  void switchTheme() {
    _isDark = !_isDark;
    notifyListeners();
  }
}

How can I access the MyTheme Provider in the child of the MultiProvider?

If it is not possible, what is the better way to do it?

Wrap MaterialApp in a Builder

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (context) => Result(),
        ),
        ChangeNotifierProvider(
          create: (context) => MyTheme(),
        ),
      ],
      child: Builder(
        builder: (context) => MaterialApp(
          home: TasksScreen(),
          theme: ThemeData.light(),
          darkTheme: ThemeData.dark(),
          themeMode: context.watch<MyTheme>().currentTheme(),
        ),
      ),
    );
  }
}

使用提供者

var theme = Provider.of<MyTheme>(context, listen: false).currentTheme();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM