LoginSignup
47
29

More than 5 years have passed since last update.

Flutterでウィジェットを重ねて表示する方法

Posted at

アプリを作っているとこんな感じで、画像の上にテキストやボタンを重ねて表示したいことがあります。
本エントリはFlutterでこのレイアウトを実現する方法の紹介です。

ウィジェットを重ねるにはStackウィジェットを使います。
Stackchildrenに重ねたいウィジェトの配列を指定します。最初の要素ほど、最初に配置されます(奥に配置される)。
またfitプロパティをStackFit.expandにすることで、全画面に表示されるようにしています。

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Stack(
          children: <Widget>[
            new Image.asset("assets/comp.jpg",
              fit: BoxFit.cover,
            ),
            new Align(
              alignment: new Alignment(0.0, 1.0),
              child: Container(
                margin: new EdgeInsets.only(bottom: 30.0),
                child: new RaisedButton(
                  onPressed: () {
                    print("pressed");
                  },
                  child: new Text("YES YES YES",
                    style: new TextStyle(color: Colors.white),
                  ),
                  color: Colors.pink[500],
                ),
              ),
            ),
            new Center(
              child: new Container(
                margin: new EdgeInsets.all(30.0),
                child: new Text("Let's Cooking!!",
                  style: new TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 50.0,
                    color: Colors.pink[500],
                  ),),
              ),
            )
          ],
          fit: StackFit.expand
      ),
    );
  }

fitプロパティをStackFit.expandにしたことで、childrenの全てのウィジェットのサイズが全画面になってしまっているので、それぞれ適切な位置になるように以下の方法で調整しています。

  • CenterウィジェットでLet's Cookingを画面中央に配置
  • Alignウィジェットで垂直方向を下寄せにして、YES YES YESボタンが画面の下部に配置

ネイティブや他のフレームワークでもそうですが、何通りも実現する方法はありそうです。
とりあえずビギナーの私が最初に見つけた方法がこちらです。

このレイアウト作って感じたのは、結構ウィジェットのネストが深くなりがちだなーってことです。

47
29
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
47
29