Changing backgroundcolor depending on variable in flutter

一曲冷凌霜 提交于 2021-01-29 08:47:59

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!