18

我有一个定位的 Text 元素,它位于 Stack 中的 Image 元素之上。我想对该 Text 元素应用一个简单的背景颜色,以便它像标题框一样框住文本:

期望的输出

我可以通过在该堆栈中插入一个容器作为另一个定位的孩子来做到这一点。但是每次文本字符串更改时,我都必须重新计算宽度,这是次优的。有没有更好的办法?

一种糟糕的方法

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,
    )
  ]
);
4

2 回答 2

17

只需将 Text 元素作为子元素嵌套在具有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,
    ),
  ]
);
于 2017-01-11T05:13:52.010 回答
7

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

于 2018-11-05T16:01:12.363 回答