简体   繁体   English

如何调用ThemeService themeService = Provider.of(context); 在脚手架的初始状态?

[英]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.我已经使用 provider 设置了两个主题,并在按下按钮或设置状态时调用它们。 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我会查看这个答案以获取更多信息: 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:从本质上讲,你可以使用didChangeDependencies方法(它获取后立即叫initState ),或内部initState ,你可以使用这样的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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