简体   繁体   中英

How to call ThemeService themeService = Provider.of(context); in the initial state of a scaffold?

I am new to flutter. my question is that how do I switch themes in the initial state of my scaffolds? I already have set up a two themes using provider and I call them on button press or set state. but I'm looking for something more convenient as in changing the theme in initial state. here is my theme code using provider

class ThemeService with ChangeNotifier {
  static final ThemeData themeA =
      ThemeData.light().copyWith(scaffoldBackgroundColor: Colors.black);
  static final ThemeData themeB =
      ThemeData.light().copyWith(scaffoldBackgroundColor: Colors.white);

  ThemeData _currentTheme = themeA;

  get currentTheme => _currentTheme;

  switchToThemeA() {
    _currentTheme = themeA;
    notifyListeners();
  }

  switchToThemeB() {
    _currentTheme = themeB;
    notifyListeners();
  }
}

every-time I want to change theme I call this

ThemeService themeService = Provider.of<ThemeService>(context);
themeService.switchToThemeB();

this works fine on button presses and set state but I am unable to call this in initial state. can someone help me?

I would look at this answer for more information: Flutter get context in initState method

Essentially, you can use the didChangeDependencies method (which gets called right after initState ) or, inside of initState , you could use something like:

void initState() {
  ...
  SchedulerBinding.instance.addPostFrameCallback((_) {
    ThemeService themeService = Provider.of<ThemeService>(context);
  });
  ...
}

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