问题
With Flutter i want to change the backgroundcolor of my app whenever the value of "color" variable changes.
String color = "white";
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.green,
I don't know how to set color to backgroundColor proprety.
回答1:
To store your color value, you can use Color
type data:
Color myColor = Colors.white;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: myColor,
After that, you can change the myColor property, and your backgroundColor
will also be changed.
I hope it will be helpful.
回答2:
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(),
);
}
}
来源:https://stackoverflow.com/questions/63349525/changing-backgroundcolor-depending-on-variable-in-flutter