我正在使用颤振项目 我想使用onpressed
事件更改主题颜色
我尝试了一些代码,但不起作用。
主镖文件
import 'package:flutter/material.dart';
import 'Screens/HomePage.dart';
void main()=> runApp(MyApp());
ThemeData _lightTheme = ThemeData(
brightness: Brightness.light,
primaryColor: Colors.white,
);
ThemeData _darkTheme = ThemeData(
brightness: Brightness.light,
primaryColor: Colors.white,
);
bool _ktheme = true;
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Wallbay',
theme: _ktheme ? _lightTheme : _darkTheme,
home: MyHomePage('Alpha Papers'),
);
}
}
主页.dart文件
........
IconButton(
icon: Icon(Icons.brightness_medium_outlined),
onPressed: () {
setState(() {
_ktheme = !ktheme;
});
},
)
......
您的主题对象_lightTheme
和_darkTheme
是具有不同名称的相同对象。
他们都brightness
设置为Brightness.light
primaryColor
Colors.white
。
ThemeData _lightTheme = ThemeData(
brightness: Brightness.light, // <----
primaryColor: Colors.white, // <----
);
ThemeData _darkTheme = ThemeData(
brightness: Brightness.light, // <--- Dark mode having light brightness
primaryColor: Colors.white, // <---- Dark mode having white color
);
将这些更改为以下内容:
ThemeData _lightTheme = ThemeData(
brightness: Brightness.light, // light mode
primaryColor: Colors.white,
);
ThemeData _darkTheme = ThemeData(
brightness: Brightness.dark, // dark mode
primaryColor: Colors.black,
);
此外,您的onPressed
代码看起来有问题。
setState(() {
_ktheme = !_ktheme; // Notice: I renamed ktheme to _ktheme
});