世界最大級のオンライン学習サービス「Udemy」のセール状況はこちら

【Flutter】Stackの使い方|ウィジェットを積み重ねて表示

こんにちは、フラメルです。

今回はウィジェットを積み重ねて表示できるStackの使い方を紹介します。

目次

Stackの使い方

Stackではchildrenに積み重ねて表示させたいウィジェットを下層から順に追加します。

Stack(
  children: [
    Container(
      width: 300,
      height: 300,
      color: Colors.red,
    ),
    Container(
      width: 200,
      height: 200,
      color: Colors.green,
    ),
    Container(
      width: 100,
      height: 100,
      color: Colors.blue,
    )
  ],
),

積み重ねる要素の位置を指定

AlignmentDirectional.bottomCenter
AlignmentDirectional.centerEnd

積み重ねる要素の位置を指定するにはalignmentを使用します。

下記コードではalignmentAlignmentDirectional.bottomCenterを渡して中央下に要素を重ねています。

Stack(
  alignment: AlignmentDirectional.bottomCenter,
  children: [
    Container(
      width: 300,
      height: 300,
      color: Colors.red,
    ),
    Container(
      width: 200,
      height: 200,
      color: Colors.green,
    ),
    Container(
      width: 100,
      height: 100,
      color: Colors.blue,
    )
  ],
),

要素別に位置を指定

要素別に位置を指定したい場合はPositionedを使用します。

Stack(
  children: [
    Container(
      width: 300,
      height: 300,
      color: Colors.red,
    ),
    Positioned(
      top: 50,
      left: 0,
      child: Container(
        width: 200,
        height: 200,
        color: Colors.green,
      ),
    ),
    Positioned(
      top: 100,
      left: 150,
      child: Container(
        width: 100,
        height: 100,
        color: Colors.blue,
      ),
    )
  ],
),

サンプルコード

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Flutter')),
        body: Center(
          child: Stack(
            children: [
              Container(
                width: 300,
                height: 300,
                color: Colors.red,
              ),
              Positioned(
                top: 50,
                left: 0,
                child: Container(
                  width: 200,
                  height: 200,
                  color: Colors.green,
                ),
              ),
              Positioned(
                top: 100,
                left: 150,
                child: Container(
                  width: 100,
                  height: 100,
                  color: Colors.blue,
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

以上です。

合わせて読みたい

参考サイト

目次