0%

Flutter 判断是否在暗色模式(Dark)下

有时出于各种需要,要在运行时判断当前的主题是否处在暗色模式(brightness == Brightness.dark)下,一般情况下这样就可以了:

1
2
3
bool isDarkMode(BuildContext context) {
return Theme.of(context).brightness == Brightness.dark;
}

为什么这么做呢,因为 theme_data.dart 中就有一句:

1
final bool isDark = _brightness == Brightness.dark;

那为什么说 一般情况下 呢,还是看 theme_data.dart

1
final Brightness _brightness = brightness ?? colorScheme?.brightness ?? Brightness.light;

所以有时候,需要这样做:

1
2
3
bool isDarkMode(BuildContext context) {
return Theme.of(context).colorScheme.brightness == Brightness.dark;
}