有时出于各种需要,要在运行时判断当前的主题是否处在暗色模式(brightness == Brightness.dark)下,一般情况下这样就可以了:
bool isDarkMode(BuildContext context) {
return Theme.of(context).brightness == Brightness.dark;
}
为什么这么做呢,因为 theme_data.dart 中就有一句:
final bool isDark = _brightness == Brightness.dark;
那为什么说 一般情况下 呢,还是看 theme_data.dart :
final Brightness _brightness = brightness ?? colorScheme?.brightness ?? Brightness.light;
所以有时候,需要这样做:
bool isDarkMode(BuildContext context) {
return Theme.of(context).colorScheme.brightness == Brightness.dark;
}
本文介绍了在Flutter应用中如何检测当前主题是否为暗色模式。通过两种方法实现:一是直接检查Theme.of(context).brightness,二是检查Theme.of(context).colorScheme.brightness。这两种方法确保了在不同场景下都能准确判断。
1478

被折叠的 条评论
为什么被折叠?



