18

Stack 内の Image 要素の上に配置された Text 要素があります。その Text 要素にシンプルな背景色を適用して、キャプション ボックスのようにテキストを囲みたいと思います。

希望の出力

これを行うには、Container を別の配置された子としてその Stack に挿入します。しかし、テキスト文字列が変更されるたびに幅を再計算する必要があり、これは最適ではありません。より良い方法はありますか?

1 つの貧弱なアプローチ

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

BoxDecoration (つまり、背景色) を持つ Containerの子として 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(
        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 に答える