Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Container: cannot provide both a color and a decoration

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?

like image 282
Suragch Avatar asked Dec 08 '18 01:12

Suragch


People also ask

Can we use color and decoration property simultaneously in the container?

The color and decoration arguments cannot both be supplied, since it would potentially result in the decoration drawing over the background color.

How do you add an image to container decoration in flutter?

To set an image background for a Container widget in Flutter, we set its decoration property like this: decoration: const BoxDecoration( image: DecorationImage( image: NetworkImage(/*... */), fit: BoxFit. cover, repeat: ImageRepeat.


2 Answers

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.

like image 51
Suragch Avatar answered Sep 20 '22 05:09

Suragch


The color property is a shorthand for creating a BoxDecoration with a color field. If you are adding a box decoration, simply place the color on the BoxDecoration.

assert(color == null || decoration == null,   'Cannot provide both a color and a decoration\n'   'To provide both, use "decoration: BoxDecoration(color: color)".' ), 

So if you have used the BoxDecoration in the Container, then you have to remove the color parameter from the Container and add to it in the BoxDecoration

          Container(               decoration: BoxDecoration(                 color: Colors.yellow,               ),            // color: Colors.yellow,           ) 
like image 38
Paresh Mangukiya Avatar answered Sep 23 '22 05:09

Paresh Mangukiya