ChangeNotifierProvider没有被调用

时间:2019-10-22 15:08:05

标签: android-studio flutter dart listener provider

未调用我的ChangeNotifierProvider。...


  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<MyGlobals>(
        builder: (context) => MyGlobals(),
        child: MaterialApp(
          theme: MyGlobals().GetTheme() == "dark" ? ThemeData(fontFamily: 'ERAS', primaryColor: Colors.black, accentColor: Colors.amberAccent, secondaryHeaderColor: Colors.black54):
          ThemeData(fontFamily: 'ERAS', primaryColor: Colors.white, accentColor: Colors.black, secondaryHeaderColor: Colors.white70),
          home: MyHomePage(),
        ));
  }
}

这是MyGlobals:

String _theme = "dark";

class MyGlobals with ChangeNotifier {


  getTheme() => _theme;


  void setTheme(String _themecolor) {
    _theme = _themecolor;
    notifyListeners();
  }
}

我没有得到任何错误,只是没有被调用。我正在从另一个.dart文件中调用setTheme,并且未调用它not changenotifierprovider。 MyGlobals是与上面的ChangeNotifierProvider代码分开的.dart文件。

1 个答案:

答案 0 :(得分:0)

您需要一个Consumer小部件来监听您在Model中所做的更改,如下所示:

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<MyGlobals>(
      builder: (context) => MyGlobals(),
      child: Consumer<MyGlobals>(
        builder: (_, model, __) {
          return MaterialApp(
            theme: model.getTheme() == "dark"
                ? ThemeData(
                    fontFamily: 'ERAS',
                    primaryColor: Colors.black,
                    accentColor: Colors.amberAccent,
                    secondaryHeaderColor: Colors.black54)
                : ThemeData(
                    fontFamily: 'ERAS',
                    primaryColor: Colors.white,
                    accentColor: Colors.black,
                    secondaryHeaderColor: Colors.white70),
            home: MyHomePage(),
          );
        },
      ),
    );
  }

然后您可以通过以下方式更新主题:

Provider.of<MyGlobals>(context).setTheme("your_theme")