如何设置定位文本块的背景颜色?

bko*_*ash 12 dart flutter

我有一个定位的Text元素,它位于Stack中的Image元素之上.我想将一个简单的背景颜色应用于该Text元素,以便它像文本框一样构成文本框架:

期望的输出

我可以通过在该堆栈中插入一个Container作为另一个定位子项来完成此操作.但是每次文本字符串更改时我都必须重新计算宽度,这是次优的.有没有更好的办法?

一个糟糕的方法

var stack = new Stack(
  children: <Widget>[
    new Image.asset ( // background photo
      "assets/texture.jpg",
      fit: ImageFit.cover,
      height: 600.0,
    ),
    new Positioned ( // headline
      child: new Container(
        decoration: new BoxDecoration (
          backgroundColor: Colors.black
        ),
      ),
      left: 0.0,
      bottom: 108.0,
      width: 490.0,
      height: 80.0,
    ),
    new Positioned (
      child: new Text (
        "Lorem ipsum dolor.",
        style: new TextStyle(
          color: Colors.blue[500],
          fontSize: 42.0,
          fontWeight: FontWeight.w900
        )
      ),
      left: 16.0,
      bottom: 128.0,
    )
  ]
);
Run Code Online (Sandbox Code Playgroud)

bko*_*ash 14

只是窝文本元素作为子具有BoxDecoration(即背景色)的容器; 容器将拉伸以适应文本内部.另外,可以为该Container指定填充,这消除了对盒子的宽度/高度进行硬编码的需要.

var stack = new Stack(
  children: <Widget>[
    new Image.asset ( // background photo
      "assets/texture.jpg",
      fit: ImageFit.cover,
      height: 600.0,
    ),
    new Positioned ( // headline
      child: new Container(
        child: new Text (
          "Lorem ipsum dolor.",
          style: new TextStyle(
            color: Colors.blue[500],
            fontSize: 42.0,
            fontWeight: FontWeight.w900
          )
        ),
        decoration: new BoxDecoration (
          backgroundColor: Colors.black
        ),
        padding: new EdgeInsets.fromLTRB(16.0, 16.0, 16.0, 16.0),
      ),
      left: 0.0,
      bottom: 108.0,
    ),
  ]
);
Run Code Online (Sandbox Code Playgroud)


Jam*_*ite 5

从Flutter 0.10.3起更改了BoxDecoration。backgroundColor:不再是有效的属性。现在是颜色:。