Study

30. Flutter 레이아웃 완벽 가이드: 기본부터 고급까지 | Flutter

구구 구구 2024. 7. 30. 11:00
반응형

고딕 스타일, dall-e

 

 

Understanding Flutter Layouts: A Comprehensive Guide

 

01. 레이아웃 위젯의 기본 개념

1) 레이아웃 위젯의 개요

Flutter에서 레이아웃 위젯은 앱의 사용자 인터페이스를 구성하는 데 중요한 역할을 합니다. 레이아웃 위젯을 사용하면 다양한 UI 요소를 배치하고, 정렬하고, 크기를 조정할 수 있습니다. 이러한 위젯들은 복잡한 레이아웃을 쉽게 구성할 수 있도록 돕습니다.

2) 단일 위젯 배치 방법

단일 위젯을 배치하는 가장 기본적인 방법은 Container 위젯을 사용하는 것입니다. Container 위젯은 여백, 패딩, 배경색 등을 설정할 수 있으며, 하나의 자식 위젯을 포함할 수 있습니다.


import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Single Widget Layout Example'),
        ),
        body: Center(
          child: Container(
            width: 200,
            height: 200,
            color: Colors.blue,
            child: Center(
              child: Text(
                'Hello, Flutter!',
                style: TextStyle(color: Colors.white, fontSize: 20),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

출력 결과: 파란색 배경의 컨테이너 중앙에 "Hello, Flutter!"라는 흰색 텍스트가 표시됩니다.

 

02. 다중 위젯 배치

1) 수직 및 수평으로 위젯 배치하기

Flutter에서 여러 위젯을 수직 또는 수평으로 배치하려면 ColumnRow 위젯을 사용합니다. Column 위젯은 자식 위젯들을 세로로 배치하고, Row 위젯은 자식 위젯들을 가로로 배치합니다.


import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Vertical Layout Example'),
        ),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              width: 100,
              height: 100,
              color: Colors.red,
              child: Center(
                child: Text(
                  'Box 1',
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ),
            Container(
              width: 100,
              height: 100,
              color: Colors.green,
              child: Center(
                child: Text(
                  'Box 2',
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ),
            Container(
              width: 100,
              height: 100,
              color: Colors.blue,
              child: Center(
                child: Text(
                  'Box 3',
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

출력 결과: 세 개의 컬러 박스가 세로로 중앙에 배열됩니다.


import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Horizontal Layout Example'),
        ),
        body: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              width: 100,
              height: 100,
              color: Colors.red,
              child: Center(
                child: Text(
                  'Box 1',
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ),
            Container(
              width: 100,
              height: 100,
              color: Colors.green,
              child: Center(
                child: Text(
                  'Box 2',
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ),
            Container(
              width: 100,
              height: 100,
              color: Colors.blue,
              child: Center(
                child: Text(
                  'Box 3',
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

출력 결과: 세 개의 컬러 박스가 가로로 중앙에 배열됩니다.

2) Row와 Column 사용법

RowColumn 위젯은 여러 자식 위젯을 각각 가로와 세로로 배치하는 데 사용됩니다. 이 위젯들은 mainAxisAlignment, crossAxisAlignment 등의 속성을 통해 자식 위젯들의 정렬 방식을 설정할 수 있습니다.


import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Row and Column Example'),
        ),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                Icon(Icons.star, size: 50, color: Colors.red),
                Icon(Icons.star, size: 50, color: Colors.green),
                Icon(Icons.star, size: 50, color: Colors.blue),
              ],
            ),
            SizedBox(height: 20),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.favorite, size: 50, color: Colors.pink),
                Icon(Icons.favorite, size: 50, color: Colors.orange),
                Icon(Icons.favorite, size: 50, color: Colors.purple),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

출력 결과: 첫 번째 Row에는 세 개의 별 아이콘이 가로로 균등하게 배열되고, 두 번째 Row에는 세 개의 하트 아이콘이 가로로 중앙에 배열됩니다.

 

03. 위젯 정렬 및 크기 조정

1) 위젯 정렬 방법

Flutter에서는 위젯의 정렬을 다양한 방식으로 설정할 수 있습니다. 주로 사용하는 속성으로는 mainAxisAlignmentcrossAxisAlignment가 있습니다. mainAxisAlignment는 주 축(main axis)에 따라 자식 위젯을 정렬하고, crossAxisAlignment는 교차 축(cross axis)에 따라 자식 위젯을 정렬합니다. RowColumn 위젯에서 이러한 속성을 사용하여 위젯을 정렬할 수 있습니다.


import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Alignment Example'),
        ),
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Container(
              height: 100,
              color: Colors.red,
              child: Center(child: Text('Box 1')),
            ),
            Container(
              height: 100,
              color: Colors.green,
              child: Center(child: Text('Box 2')),
            ),
            Container(
              height: 100,
              color: Colors.blue,
              child: Center(child: Text('Box 3')),
            ),
          ],
        ),
      ),
    );
  }
}

출력 결과: 세 개의 컨테이너가 세로로 정렬되고, 각 컨테이너의 너비는 화면 전체를 차지합니다.

2) 위젯 크기 조정 및 확장 방법

Flutter에서 위젯의 크기를 조정하고 확장하는 데 자주 사용하는 위젯은 ExpandedFlexible입니다. Expanded 위젯은 부모의 남은 공간을 모두 차지하도록 자식을 확장하고, Flexible 위젯은 자식의 크기를 조정하지만 공간을 차지할 때 유연성을 제공합니다.


import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Size Adjustment Example'),
        ),
        body: Column(
          children: [
            Expanded(
              child: Container(
                color: Colors.red,
                child: Center(child: Text('Expanded')),
              ),
            ),
            Flexible(
              child: Container(
                color: Colors.green,
                child: Center(child: Text('Flexible')),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

출력 결과: 첫 번째 컨테이너는 화면의 남은 공간을 모두 차지하고, 두 번째 컨테이너는 화면의 남은 공간을 유연하게 차지합니다.

 

04. 주요 레이아웃 위젯 소개

1) Container 위젯

Container 위젯은 Flutter에서 가장 기본적인 레이아웃 위젯으로, 다른 위젯을 포함할 수 있는 사각형 영역을 제공합니다. 여백, 패딩, 배경색, 경계선 등을 설정할 수 있습니다.


import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Container Example'),
        ),
        body: Center(
          child: Container(
            width: 200,
            height: 200,
            padding: EdgeInsets.all(16.0),
            margin: EdgeInsets.all(16.0),
            color: Colors.blue,
            child: Center(
              child: Text(
                'Hello, Flutter!',
                style: TextStyle(color: Colors.white, fontSize: 20),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

출력 결과: 파란색 배경의 컨테이너가 중앙에 표시되고, 그 안에 "Hello, Flutter!"라는 흰색 텍스트가 포함됩니다.

2) GridView 위젯

GridView 위젯은 스크롤 가능한 그리드 레이아웃을 만드는 데 사용됩니다. 행과 열을 사용하여 자식 위젯들을 배치할 수 있습니다.


import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  final List items = List.generate(50, (i) => "Item $i");

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('GridView Example'),
        ),
        body: GridView.builder(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
          ),
          itemCount: items.length,
          itemBuilder: (context, index) {
            return Card(
              child: Center(
                child: Text('${items[index]}'),
              ),
            );
          },
        ),
      ),
    );
  }
}

출력 결과: 50개의 항목이 스크롤 가능한 그리드 레이아웃에 표시됩니다.

3) ListView 위젯

ListView 위젯은 스크롤 가능한 리스트를 만드는 데 사용됩니다. 많은 양의 데이터를 표시할 때 유용합니다.


import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  final List items = List.generate(100, (i) => "Item $i");

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('ListView Example'),
        ),
        body: ListView.builder(
          itemCount: items.length,
          itemBuilder: (context, index) {
            return ListTile(
              title: Text('${items[index]}'),
            );
          },
        ),
      ),
    );
  }
}

출력 결과: 100개의 항목이 스크롤 가능한 리스트에 표시됩니다.

4) Stack 위젯

Stack 위젯은 자식 위젯들을 서로 겹쳐서 배치하는 데 사용됩니다. 각 자식의 위치를 설정하여 복잡한 레이아웃을 만들 수 있습니다.


import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Stack Example'),
        ),
        body: Center(
          child: Stack(
            alignment: Alignment.center,
            children: [
              Container(
                width: 200,
                height: 200,
                color: Colors.blue,
              ),
              Container(
                width: 150,
                height: 150,
                color: Colors.red,
              ),
              Container(
                width: 100,
                height: 100,
                color: Colors.yellow,
              ),
            ],
          ),
        ),
      ),
    );
  }
}

출력 결과: 세 개의 컨테이너가 중앙에서 겹쳐져 배치됩니다.

 

05. Material 디자인 컴포넌트

1) Card 위젯

Card 위젯은 Material 디자인에서 제공하는 카드 레이아웃을 구현합니다. 카드 레이아웃은 정보나 상호작용 요소들을 시각적으로 구분할 수 있는 깔끔한 방법을 제공합니다.


import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Card Example'),
        ),
        body: Center(
          child: Card(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                ListTile(
                  leading: Icon(Icons.album),
                  title: Text('Card Title'),
                  subtitle: Text('Card Subtitle'),
                ),
                ButtonBar(
                  children: [
                    FlatButton(
                      child: Text('ACTION 1'),
                      onPressed: () {},
                    ),
                    FlatButton(
                      child: Text('ACTION 2'),
                      onPressed: () {},
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

출력 결과: 카드 레이아웃에 제목, 부제목, 아이콘 및 버튼이 포함된 카드가 표시됩니다.

2) ListTile 위젯

ListTile 위젯은 제목, 부제목, 아이콘 등을 포함할 수 있는 하나의 행을 제공합니다. ListTile은 리스트 항목을 구성하는 데 자주 사용됩니다.


import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('ListTile Example'),
        ),
        body: ListView(
          children: [
            ListTile(
              leading: Icon(Icons.map),
              title: Text('Map'),
              subtitle: Text('Map Description'),
            ),
            ListTile(
              leading: Icon(Icons.photo_album),
              title: Text('Album'),
              subtitle: Text('Album Description'),
            ),
            ListTile(
              leading: Icon(Icons.phone),
              title: Text('Phone'),
              subtitle: Text('Phone Description'),
            ),
          ],
        ),
      ),
    );
  }
}

출력 결과: 각 항목에 아이콘, 제목, 부제목이 포함된 세 개의 리스트 항목이 표시됩니다.

 

06. 결론

1) Flutter 레이아웃 활용의 이점

Flutter의 레이아웃 시스템은 강력하고 유연하여 다양한 사용자 인터페이스를 손쉽게 구축할 수 있게 해줍니다. Flutter 레이아웃을 활용하면 다음과 같은 이점을 얻을 수 있습니다.

  • 다양한 레이아웃 옵션: Flutter는 다양한 레이아웃 위젯을 제공하여 복잡한 UI를 쉽게 구성할 수 있습니다.
  • 일관된 디자인: Flutter의 레이아웃 위젯을 사용하면 다양한 디바이스와 화면 크기에서도 일관된 디자인을 유지할 수 있습니다.
  • 효율적인 UI 구축: Flutter의 Hot Reload 기능을 통해 UI 변경 사항을 즉시 확인하고, 빠르게 UI를 구축할 수 있습니다.
  • Material 디자인과 iOS 스타일 지원: Flutter는 Material 디자인 컴포넌트와 Cupertino 위젯을 통해 Android와 iOS 모두에서 일관된 사용자 경험을 제공합니다.

2) 추가 학습 자료 및 참고 링크

Flutter의 다양한 레이아웃 위젯과 기능을 더 깊이 이해하고 활용하기 위해 다음의 자료를 참고하세요.

이와 같은 자료를 통해 Flutter의 다양한 레이아웃 위젯을 효과적으로 사용하고, 보다 복잡하고 매력적인 앱을 개발할 수 있습니다. Flutter 레이아웃을 마스터하여 앱 개발의 효율성과 성능을 높여보세요.

 


관련된 다른 글도 읽어보시길 추천합니다

 

2024.07.25 - [Study] - 28. Flutter로 사용자 인터페이스 구축하기 | Flutter

 

28. Flutter로 사용자 인터페이스 구축하기 | Flutter

Flutter로 사용자 인터페이스 구축하기: 기본 가이드 01. 서론1) Flutter의 인기와 장점Flutter는 Google에서 개발한 오픈 소스 UI 소프트웨어 개발 키트(SDK)입니다. Flutter의 가장 큰 장점 중 하나는 한 번

guguuu.com

2024.07.24 - [Study] - 27. Windows에서 Flutter로 Android 앱 개발 시작하기: 단계별 가이드 | Flutter

 

27. Windows에서 Flutter로 Android 앱 개발 시작하기: 단계별 가이드 | Flutter

Windows에서 Flutter로 Android 앱 개발 시작하기: 단계별 가이드 01. 서론1) Flutter와 Windows 환경에서의 개발Flutter는 Google에서 개발한 오픈소스 UI 소프트웨어 개발 키트로, 단일 코드베이스를 통해 iOS, A

guguuu.com

2024.06.27 - [Study] - 01. HTML 요소와 속성 완벽 가이드 | 웹 개발 기초

 

01. HTML 요소와 속성 완벽 가이드 | 웹 개발 기초

01. 서론1) HTML이란?HTML(하이퍼텍스트 마크업 언어, HyperText Markup Language)은 웹 페이지의 구조를 정의하는 마크업 언어입니다. 웹 페이지는 텍스트, 이미지, 링크 등 다양한 요소로 구성되며, 이러한

guguuu.com


읽어주셔서 감사합니다

공감은 힘이 됩니다

 

:)

반응형