Dart,Flutter : Meaning of const modifier,Isn't Colors.yellow [200] a constant?

Viewed 351
Widget iconOfAnonymousUsers = CircleAvatar(
  radius: 100.0,
  //backgroundColor: Colors.indigo[200],
  backgroundColor: Colors.yellow[200],
  child: Stack(
    children: [
      //Center(child: Icon(Icons.person_outline)),
      Text("anonymous",
          style: TextStyle(
            fontSize: 30.0,
            color: Colors.black,
          )),
    ],
  ),
);

The above iconOfAnonymousUsers can have the const modifier,
so I thought it would be better to add it,
and when I added it.

const Widget iconOfAnonymousUsers = CircleAvatar(
  radius: 100.0,
  //backgroundColor: Colors.indigo[200],
  backgroundColor: Colors.yellow[200],
  child: Stack(
    children: [
      //Center(child: Icon(Icons.person_outline)),
      Text("anonymous",
          style: TextStyle(
            fontSize: 30.0,
            color: Colors.black,
          )),
    ],
  ),
);

Then I got the following error. enter image description here

I don't think there are any non-const components of iconOfAnonymousUsers, but are there any non-const components?
I'm not sure why the error is occurring.

enter image description here

I'm already getting an error in the above code, isn't Colors.yellow [200] a constant?

2 Answers

MaterialColor yellow is constant but not its underlying color map.
If you take a look inside the implementation of MaterialColor yellow,
you will find that its color map <int, Color>{...} is not const qualified.

static const MaterialColor yellow = MaterialColor(
_yellowPrimaryValue,
<int, Color>{
   50: Color(0xFFFFFDE7),
  100: Color(0xFFFFF9C4),
  200: Color(0xFFFFF59D),
  300: Color(0xFFFFF176),
  400: Color(0xFFFFEE58),
  500: Color(_yellowPrimaryValue),
  600: Color(0xFFFDD835),
  700: Color(0xFFFBC02D),
  800: Color(0xFFF9A825),
  900: Color(0xFFF57F17),
});

By doc, if you use Colors.yellow, it return a const MaterialColor. However, when you use Colors.yellow[200] or Colors.yellow.shade200, it return Color, not const

Related