首页 > 解决方案 > 根据颤动中的变量更改背景颜色

问题描述

使用 Flutter,每当“颜色”变量的值发生变化时,我想更改我的应用程序的背景颜色。

 String color = "white";

@override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.green,

我不知道如何将颜色设置为 backgroundColor 属性。

标签: flutterdart

解决方案


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(),
        );
      }
    }

推荐阅读