Flutter: center Widgets or components in the middle

루시Soo의 우와한 서재·2022년 5월 15일
0

Overview

위젯이나 구성요소들을 센터에 정렬하는 방법은 여러가지가 있다.
센터정렬하는 방법들을 소개해 본다.

  • Using a Center widget

  • Using a Align widget with its alignment property

  • Adding a Column with mainAxisAlignment

  • Expanded()를 이용하는 방법

Using a Center widget

이 위젯은 자신의 child를 Vertically과 horizontally 모두 센터에 위치시킨다.
children이아니고 child를 파라미터로 가진다.

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: Scaffold(
      body: Center(
        child: Text('Hello World'),
      ),
    ),
  ));
}

Using a Align widget with its alignment property

이 위젯을 이용하면 파라미터인 alignment를 이용해서 child를 화면의 여러 위치로 정렬할 수 있다.

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: Scaffold(
      body: Align(
        // 아래코드는 Align Class의 default값이기 때문에 생략 가능
        // bottomCenter이 외에도 .bottomLeft, .topCenter 등등
        // 여러가지를 선택할 수 있다.
        alignment: Alignment.center,
        child: Text('Hello World'),
      ),
    ),
  ));
}

Adding a Column with mainAxisAlignment

주의점⚠️ Column()의 상위 위젯인 Container()에 width를 width: MediaQuery.of(context).size.width,width: double.infinity,로 지정해주지 않으면 화면에서 Text()가 vertical만 cneter이고 horizontal은 center가 아니게 rendering된다.

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: Scaffold(
      body: Container(
        // DartPad는 시뮬레이션용이기 때문에 아래코드를 사용하면 에러가 발생
        //width: MediaQuery.of(context).size.width,
        width: double.infinity,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Hello World'),
          ],
        ),
      ), 
    ),
  ));
}

Expanded()를 이용하는 방법

해당 방법은 아래의 코드와 같이 Expanded()사이에 자식위젯으로 Row(), 부모위젯으로 Column()이 같이 사용되었을 때만 가능하다. 그리고 vertical과 horizontal모두 center정렬이 되는 것은 아니고 vertical만 가능하다.

import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      home: HomeScreen(),
    ),
  );
}

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  
  Widget build(BuildContext context) {
    return Scaffold(
        body: Column(children: [
      Expanded(
          child: Row(children: [
            // Text()를 Row() < Expanded() < Column() 순으로 감싸면 Text()안의 문구가 
            // vertical center 정렬이 된다. 
        Text('Hello Wolrd'),
      ])),
    ]));
  }
}

Reference

https://www.kindacode.com/article/flutter-vertically-center-a-widget-inside-a-container/

profile
그냥 끄적끄적 공부 정리 블로그

0개의 댓글