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

问题描述 投票:0回答:1

我是新手。我的问题是,如何在支架的初始状态下切换主题?我已经使用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();
  }
}

每次我想更改主题时,我都称呼它

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

这在按按钮和设置状态时效果很好,但是我无法在初始状态下调用它。有人可以帮助我吗?

android flutter flutter-layout
1个回答
0
投票

我将查看此答案以获取更多信息:Flutter get context in initState method

基本上,您可以使用didChangeDependencies方法(在initState之后立即调用),或者,initStateinside,您可以使用类似方法:

void initState() {
  ...
  SchedulerBinding.instance.addPostFrameCallback((_) {
    ThemeService themeService = Provider.of<ThemeService>(context);
  });
  ...
}
© www.soinside.com 2019 - 2024. All rights reserved.