【问题标题】:How to call ThemeService themeService = Provider.of(context); in the initial state of a scaffold?如何调用 ThemeService themeService = Provider.of(context);在脚手架的初始状态?
【发布时间】:2019-12-09 20:33:58
【问题描述】:

我是新来的颤振。我的问题是如何在脚手架的初始状态下切换主题?我已经使用提供程序设置了两个主题,并在按钮按下或设置状态时调用它们。但我正在寻找更方便的东西,比如在初始状态下改变主题。这是我使用提供者的主题代码

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();

这在按钮按下和设置状态时工作正常,但我无法在初始状态下调用它。有人可以帮我吗?

【问题讨论】:

  • 您尝试在initState 方法中设置此项?

标签: android flutter flutter-layout


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2021-10-18
    • 2020-09-18
    • 2019-05-02
    • 2019-05-08
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 2019-01-26
    相关资源
    最近更新 更多