问题描述
使用Flutter,我想在“颜色”变量的值更改时更改应用程序的背景色。
String color = "white";
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.green,
我不知道如何将颜色设置为backgroundColor属性。
解决方法
要存储颜色值,可以使用Color
类型数据:
Color myColor = Colors.white;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: myColor,
此后,您可以更改myColor属性,您的backgroundColor
也将更改。
我希望这会有所帮助。
,class AppColor {
static const RED = "RED";
static const GREEN = "GREEN";
static const BLUE = "BLUE";
static const DEFAULT = "DEFAULT";
static const _colorMap = {
RED: Colors.red,GREEN: Colors.green,BLUE: Colors.blue,DEFAULT: Colors.teal,};
const AppColor._();
static getColorFor(String color) => _colorMap[color.toUpperCase()] ?? _colorMap[DEFAULT];
}
class SO extends StatelessWidget {
var color = 'red';
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: AppColor.getColorFor(color),appBar: AppBar(),);
}
}