dart - 如何格式化定位文本 block 的背景颜色?

我有一个定位的 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,
    )
  ]
);

最佳答案

只需将 Text 元素作为子元素嵌套在 具有 BoxDecoration(即背景颜色)的 Container 中;容器将拉伸(stretch)以适合里面的文本。此外,可以为该容器指定填充,这样就无需硬编码盒子的宽度/高度。

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

https://stackoverflow.com/questions/41583111/

相关文章:

android - 如何使用 Flutter 构建增强现实应用程序?

dart - 为桌面构建 Flutter 应用程序

gridview - Flutter GridView 页脚(用于指示无限滚动的负载)

android - 如何在 Flutter 中获取 AppBar 高度

flutter - 如何在 flutter 小部件测试中捕获来自 future 的错误?

listview - Flutter:SimpleDialog 中的 ListView

ios - 在 Flutter 中打开原生 UIViewController

google-maps - 如果可以使用 flutter 打开谷歌地图应用程序

flutter - 如何在 flutter 中获得唯一的设备ID?

android - Flutter - 导航到新屏幕,并清除所有以前的屏幕