【问题标题】:ThemeSwitcher : Null check operator used on a null value, when want to switch app theme between light and dark themeThemeSwitcher : 当想要在浅色和深色主题之间切换应用程序主题时,用于空值的空检查运算符
【发布时间】:2022-01-06 17:14:59
【问题描述】:

当我点击按钮更改应用主题时,出现此错误:

The following _CastError was thrown while handling a gesture: 
Null check operator used on a null value

这是我的代码,我正在使用 ThemeSwitcher 包:

 AppBar buildAppBar(BuildContext context, bool isEdit) {
  final icon = CupertinoIcons.moon_stars;
  final isDarkMode = Theme.of(context).brightness == Brightness.dark;

  return AppBar(
    leading: IconButton(
      onPressed: () {
        if (isEdit == true) Navigator.pop(context);
      },
      icon: Icon(Icons.arrow_back),
    ),
    backgroundColor: Colors.transparent,
    elevation: 0,
    actions: [
      ThemeSwitcher(
        clipper: ThemeSwitcherBoxClipper(),
        builder: (context) => IconButton(
          icon: Icon(icon),
          // Button to change theme
          onPressed: () {
            final theme = isDarkMode ? Themes.lightTheme : Themes.darkTheme;

            // originally, there is a '!' on the switcher context below, but it says switcher context can never be null.
            final switcher = ThemeSwitcher.of(context);

            switcher.changeTheme(theme: theme, isReversed: false); //this is the code that the error pointed.
          },
        ),
      ),
    ],
  );
}

那么我该如何解决这个错误呢?我通过观看 youtube 上的教程获得了这段代码,并且我编写了完全相同的代码。

【问题讨论】:

  • 能否附上包链接
  • 我使用了 animated_theme_switcher:^2.0.6。但现在已经解决了。原来我从错误的包中获得了 main.dart 中的 ThemeProvider。我想从动画主题切换器中选择,但我从 ThemeProvider Package 中选择了 ThemeProvider。

标签: flutter dart themes flutter-dependencies


【解决方案1】:

参考animated_theme_switcher的自述文件

您必须在 MaterialApp 上方声明 ThemeProvider 以使 ThemeSwitcher 从小部件级别下方访问

所以请务必先这样做

ThemeProvider(
      initTheme: initTheme,
      builder: (context, myTheme) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: myTheme,
          home: MyHomePage(),
        );
      }),
    ),

其中 initTheme 是应用程序的默认主题或依赖于这样的系统主题

 final isPlatformDark =
        WidgetsBinding.instance!.window.platformBrightness == Brightness.dark;
    final initTheme = isPlatformDark ? ThemeData.dark() : ThemeData.light();

请参阅this 示例了解如何编辑默认主题

【讨论】:

  • 谢谢你。事实证明,我从错误的包中获得了 ThemeProvider。我想从动画主题切换器中选择,但我从 ThemeProvider Package 中选择了 ThemeProvider。
  • 你的 wlc,快乐编码@EnricoAntonio
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-10
  • 2021-06-04
相关资源
最近更新 更多