Flutter Container: cannot provide both a color and a decoration
Asked Answered
S

2

37

I want to draw a border around my container and have the background be colored.

Widget bodyWidget() {
  return Container(
    color: Colors.yellow,
    decoration: BoxDecoration(
      border: Border.all(color: Colors.black),
    ),
    child: Text("Flutter"),
  );
}

But when I try this I get the error

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

How is this solved?

Stowage answered 8/12, 2018 at 1:18 Comment(0)
S
73

Remove the color parameter from the Container and add it to the BoxDecoration:

Widget bodyWidget() {
  return Container(
    decoration: BoxDecoration(
      color: Colors.yellow,
      border: Border.all(color: Colors.black),
    ),
    child: Text("Flutter"),
  );
}

enter image description here

If you check the Container source code you can see that the color parameter is just used to set the BoxDecoration color if the decoration is null.

decoration = decoration ?? (color != null ? BoxDecoration(color: color) : null),

The error you got is just a helpful reminder of that. Otherwise you would get a strange override (as was apparently the case in the past) or you might not even notice the bug.

Stowage answered 8/12, 2018 at 1:18 Comment(0)
D
1

When using the decoration property, ensure to place the color property within the decoration and not outside.

you can use like this:

 Container(
     decoration: BoxDecoration(
       color: Colors.red,
          );
Dardani answered 13/3 at 7:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.