【问题标题】:How do I format the background color for a positioned block of text?如何格式化定位文本块的背景颜色?
【发布时间】:2017-05-25 18:51:14
【问题描述】:

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

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • color 控制文本本身的颜色。这个问题是关于设置Text 小部件的背景颜色。
      • James 谈到更改 colorContainer ,而不是 Text 。从 Flutter 1.0.0 开始,您可以这样做来更改文本背景颜色:style: TextStyle(background: Paint()..color = Color(0xFF3b9c00), ),。从github issue得到这个@
      猜你喜欢
      • 1970-01-01
      • 2011-06-11
      • 2012-12-21
      • 2019-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-06
      相关资源
      最近更新 更多