在尝试使用更改通知程序类 (code) 中定义的单个实例全局属性更改应用主题时,用于监视当前应用主题的属性 _isDark
根本不会更改,即使更改函数被执行。
尝试将其定义为实例和静态,但该属性根本不更新。
也找不到!=
(不等于)operator in the Bool class
如何解决这个问题?
输出:
switchTheme() _isDark = true
Listener -> Change Theme
switchTheme() _isDark = true
Listener -> Change Theme
switchTheme() _isDark = true
Listener -> Change Theme
changeTheme.dart:
import 'package:flutter/material.dart';
class MyTheme extends ChangeNotifier{
static bool _isDark = true;//Not updating in switchTheme()
// bool _isDark = true; //Not updating in switchTheme()
void switchTheme(){
_isDark != _isDark;//Avoid unnecessary statements Android Studio
print('switchTheme() _isDark = $_isDark');
notifyListeners();
}
ThemeMode currentTheme(){
return _isDark ? ThemeMode.dark : ThemeMode.light;
}
config.dart:
library config.dart ;
import 'changeTheme.dart';
MyTheme myTheme = MyTheme();
homeScreen.dart :
import 'package:flutter/material.dart';
import 'config.dart';
import 'changeTheme.dart';
void main(){runApp(
MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.light(),
darkTheme: ThemeData.dark(),
themeMode: myTheme.currentTheme(),
home: HomeScreen(),
);
}
}
class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
void initState(){
super.initState();
myTheme.addListener(() {
print('Listener -> Change Theme');
setState(() {
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children : [
Positioned(
left: MediaQuery.of(context).size.width * 0.5,
top: MediaQuery.of(context).size.height * 0.5,
child: Container(
width: MediaQuery.of(context).size.width * 0.1,
height: MediaQuery.of(context).size.height * 0.05,
child: ElevatedButton(
onPressed: (){
myTheme.switchTheme();
} ,
style: ButtonStyle(backgroundColor: MaterialStateProperty.all(Colors.orangeAccent)),
child: Text('Change Theme '),
),
),
),
]) );
}
}
答案 0 :(得分:1)
当你想切换主题时,使用 _isDark = !_isDark;
(而不是 !=
)来改变一个布尔值和它的对立面。