Flutter Container:不能同时提供颜色和装饰

Sur*_*gch 3 flutter flutter-container

我想在容器周围绘制边框,并为背景着色。

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

但是当我尝试这个时我得到了错误

无法同时提供颜色和装饰
color参数只是“ decoration:new BoxDecoration(color:color)”的简写。

如何解决?

Sur*_*gch 9

color从容器中删除参数,并将其添加到BoxDecoration中:

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

在此处输入图片说明

如果检查Container源代码,则可以看到color如果装饰为null ,则该参数仅用于设置BoxDecoration颜色。

decoration = decoration ?? (color != null ? BoxDecoration(color: color) : null),
Run Code Online (Sandbox Code Playgroud)

您收到的错误只是一个有用的提醒。否则,您将得到一个奇怪的覆盖(就像过去那样),或者甚至可能没有注意到该错误。


Par*_*iya 5

color属性是创建BoxDecoration带有颜色字段的的简写。如果您要添加框装饰,只需将颜色放在 BoxDecoration 上。

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

所以,如果你已经使用了BoxDecorationContainer,那么你必须从去除颜色参数Container,并添加到它的BoxDecoration

          Container(
              decoration: BoxDecoration(
                color: Colors.yellow,
              ),
           // color: Colors.yellow,
          )
Run Code Online (Sandbox Code Playgroud)