我有一个定位的文本元素,它位于Stack中的Image元素的顶部.我想将简单的背景 colored颜色 应用到该文本元素,以便它将文本的边框设置为标题框:

desired output

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

one poor approach

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

推荐答案

只需将文本元素作为子元素嵌套within具有BoxDecation(即背景色)的Container;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,
    ),
  ]
);

Flutter相关问答推荐

Flutter -如何从布局填充(对称水平)中排除小部件?

Android元数据为1.9.0,预期版本为1.7.1,如何解决flutter应用程序构建失败问题?

Flutter -如何停止块监听程序在后台堆栈中运行

我不能在Fighting中裁剪图片输入错误,否则应用程序会崩溃

FOR回路中的Flutter 模型

Flutter 附近的连接

在 Flutter 中使用条件语句设置 ImageProvider Object 类型的背景图像

Flutter:使用不包含导航器的上下文请求导航器操作

更改底部导航栏下方 Flutter Snackbar 的位置

转换函数上传文件上传Uint8List

Flutter - 如何将按钮对齐到行的右侧

如何将 List 转换为 String []?

Flutter 错误:正文可能正常完成,导致返回null

如何在 Flutter 中将列小部件添加到行小部件?

在 flutter 中使用 Firebase 实时数据库数据创建无限滚动效果

Flutter 在气泡聊天消息上对齐时间戳文本

NoSuchMethodError:方法 '[]' 在 null 上被调用.我的信息流中的错误

是否可以在 Flutter 中使用 ToggleButtons 在页面 PageView 之间切换?

Flutter 平台通道将多数据传递给 windows 功能

Flutter Firebase 可以在真实设备上运行,而不是在 Android 模拟器上运行