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

【Flutter】Columnの要素を中央寄せにする方法

FlutterでColumnの要素を左寄せにする方法を紹介します。

Column基本的な使い方、知っておきたい基本プロパティのまとめ記事はこちら↓

目次

Columnの要素を中央寄せにする方法

Columnの要素を左寄せにするにはcrossAxisAlignmentを使用します。

使用方法としてはcrossAxisAlignmentの引数にCrossAxisAlignment.centerを渡します。

Column(
  crossAxisAlignment: CrossAxisAlignment.center,
  children: [
    ...
  ],
),

Columnの要素が左寄せされない場合の対処法

Columnの横幅をContainerSizedBoxなどで指定しない場合、Columnの横幅はchildrenの要素の横幅に左右され左寄せで表示されない場合があります。

そんな場合は次のようにColumnSizedBoxでラップし、widthの引数にdouble.infinityを渡します

SizedBox(
  width: double.infinity,
  child: Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: [
      Container(
        width: 150,
        height: 150,
        color: Colors.red,
      ),
      Container(
        width: 150,
        height: 150,
        color: Colors.yellow,
      ),
      Container(
        width: 150,
        height: 150,
        color: Colors.blue,
      ),
    ],
  ),
),

Centerでも要素を中央寄せできる

crossAxisAlignmentを使用せず、CenterColumnの要素を中央に表示することも可能です。

Center(
  child: Column(
    children: [
      ...
    ],
  ),
)
    

サンプルコード

import 'package:flutter/material.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(title: const Text('Flutter')),
        body: SizedBox(
          width: double.infinity,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Container(
                width: 150,
                height: 150,
                color: Colors.red,
              ),
              Container(
                width: 150,
                height: 150,
                color: Colors.yellow,
              ),
              Container(
                width: 150,
                height: 150,
                color: Colors.blue,
              ),
            ],
          ),
        ),
      ),
    );
  }
}

合わせて読みたい

参考サイト

目次