颤振主题 使用 onpress 事件将暗变为亮



我正在使用颤振项目 我想使用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.lightprimaryColorColors.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
});

相关内容

  • 没有找到相关文章

最新更新