Nielson
Nielson

Reputation: 49

Changing backgroundcolor depending on variable in flutter

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.

Upvotes: 0

Views: 2073

Answers (2)

Doc
Doc

Reputation: 11651

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

Upvotes: 2

hisam
hisam

Reputation: 1609

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.

Upvotes: 0

Related Questions