75

I have a Flutter Container widget and I defined a color for it (pink), but for some reason, the color in BoxDecoration overrides it (green). Why?

new Container(
  color: Colors.pink,
  decoration: new BoxDecoration(
    borderRadius: new BorderRadius.circular(16.0),
    color: Colors.green,
  ),
);

4 Answers 4

72

Container’s color is shorthand for BoxDecoration’s color, so BoxDecoration's color in the Container's decoration property overrides its Container's color.

2
  • 2
    i want to give blue color for border and amber for container background color, how can i do?
    – Kamlesh
    Jan 5, 2020 at 10:52
  • 2
    You can achieve like this decoration: BoxDecoration( color: Colors.yellow, border: Border.all(color: Theme.of(context).accentColor,) ), @Kamlesh Apr 24, 2020 at 7:18
28

Problem:

You can't use color and decoration at the same time. From docs:

The color and decoration arguments cannot both be supplied, since it would potentially result in the decoration drawing over the background color. To supply a decoration with a color, use decoration: BoxDecoration(color: color).


Solutions:

  • Use only color:

    Container(
      color: Colors.red
    )
    
  • Use only decoration and provide color here:

    Container(
      decoration: BoxDecoration(color: Colors.red)
    )
    
5

only set background color use this code

new Container(
  color: Colors.pink,
  
);

if set background color with radius or shape then use color inside decoration

 Container(
          decoration: BoxDecoration(
          color: Colors.red,
          borderRadius: BorderRadius.circular(17)),
child:SizeBox());
1

Flutter team says that color property in BoxDecoration() is quite frequently used in applying background color to Container widget. As such they have put a separate shorthand for color property in Container widget. So, when we use both color property and BoxDecoration() color property in same Container widget, an assertion will be thrown as follows:

Cannot provide both a color and a decoration
The color argument is just a shorthand for "decoration: new BoxDecoration(color: color)".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.