Flutter + Dart/Flutter + Dart TIP

Flutter 위젯 카탈로그

GREEN나무 2025. 5. 13. 15:11
728x90

https://docs.flutter.dev/ui/widgets


1. 디자인 시스템 (Design Systems)

Flutter는 두 가지 기본 디자인 시스템을 제공합니다.

  • Cupertino:
    iOS 및 macOS의 휴먼 인터페이스 가이드라인에 맞춘 위젯 제공
  • Material:
    Material 3 디자인 사양을 구현한 시각적, 행동적, 모션이 풍부한 위젯 제공

예시 코드 – Material Design:

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(
      title: 'Material Demo',
      home: Scaffold(
        appBar: AppBar(title: Text('Material 디자인 예제')),
        body: Center(
          child: ElevatedButton(
            onPressed: () => print('Material 버튼 클릭'),
            child: Text('클릭하세요'),
          ),
        ),
      ),
    ));

예시 코드 – Cupertino Design:

import 'package:flutter/cupertino.dart';

void main() => runApp(
      CupertinoApp(
        title: 'Cupertino Demo',
        home: CupertinoPageScaffold(
          navigationBar: CupertinoNavigationBar(
            middle: Text('Cupertino 디자인 예제'),
          ),
          child: Center(
            child: CupertinoButton(
              onPressed: () => print('Cupertino 버튼 클릭'),
              child: Text('클릭하세요'),
            ),
          ),
        ),
      ),
    );

2. 기본 위젯 (Base Widgets)

기본 위젯은 화면 구성의 핵심 요소로, 입력, 레이아웃, 텍스트 등을 다룹니다.

예시 코드 – Container와 Text 사용 예:

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(
      home: Scaffold(
        body: Center(
          child: Container(
            padding: EdgeInsets.all(16),
            color: Colors.amberAccent,
            child: Text(
              'Hello, Flutter!',
              style: TextStyle(fontSize: 20),
            ),
          ),
        ),
      ),
    ));

3. 접근성 (Accessibility)

접근성 위젯은 앱의 내용을 보조 기술(스크린 리더 등)과 쉽게 연동할 수 있도록 도와줍니다.
주요 위젯: Semantics, ExcludeSemantics, MergeSemantics

예시 코드 – Semantics 위젯 사용:

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(
      home: Scaffold(
          body: Center(
        child: Semantics(
          label: '중요한 버튼',
          button: true,
          child: ElevatedButton(
            onPressed: () {},
            child: Text('접근성 버튼'),
          ),
        ),
      )),
    ));

4. 애니메이션 및 모션 (Animation and Motion)

Flutter는 다양한 애니메이션 위젯을 제공하여 부드러운 전환과 시각적 효과를 쉽게 구현할 수 있습니다.
주요 위젯: AnimatedContainer, AnimatedOpacity, Hero, AnimatedBuilder

예시 코드 – AnimatedContainer:

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(home: AnimatedContainerExample()));

class AnimatedContainerExample extends StatefulWidget {
  @override
  _AnimatedContainerExampleState createState() =>
      _AnimatedContainerExampleState();
}

class _AnimatedContainerExampleState extends State<AnimatedContainerExample> {
  double _size = 100;
  Color _color = Colors.blue;

  void _animate() {
    setState(() {
      _size = _size == 100 ? 200 : 100;
      _color = _color == Colors.blue ? Colors.red : Colors.blue;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('애니메이션 예제')),
      body: Center(
        child: AnimatedContainer(
          duration: Duration(seconds: 1),
          width: _size,
          height: _size,
          color: _color,
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _animate,
        child: Icon(Icons.play_arrow),
      ),
    );
  }
}

5. 자산, 이미지 및 아이콘 (Assets, Images, and Icons)

앱 내에서 로컬 에셋이나 네트워크 이미지를 보여주거나, 아이콘을 표시하는 위젯입니다.
주요 위젯: Image (asset, network), Icon

예시 코드:

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('이미지 & 아이콘 예제')),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // 로컬 이미지 (assets 등록 필요)
            Image.asset('assets/images/flutter_logo.png', height: 100),
            SizedBox(height: 20),
            // 네트워크 이미지
            Image.network('https://flutter.dev/images/flutter-logo-sharing.png',
                height: 100),
            SizedBox(height: 20),
            // 아이콘
            Icon(Icons.flutter_dash, size: 50, color: Colors.blue),
          ],
        ),
      ),
    ));

6. 비동기 (Async)

비동기 처리를 위한 위젯으로, 데이터를 가져오거나 스트림을 구독할 때 유용합니다.
주요 위젯: FutureBuilder, StreamBuilder

예시 코드 – FutureBuilder:

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(home: FutureExample()));

class FutureExample extends StatelessWidget {
  Future<String> _fetchData() async {
    await Future.delayed(Duration(seconds: 2));
    return '비동기 데이터 완료!';
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('FutureBuilder 예제')),
      body: Center(
        child: FutureBuilder<String>(
          future: _fetchData(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting)
              return CircularProgressIndicator();
            else if (snapshot.hasError)
              return Text('오류 발생');
            else
              return Text(snapshot.data ?? '');
          },
        ),
      ),
    );
  }
}

7. 기초 위젯 (Basics)

Flutter 앱의 기본 구조를 이루는 위젯들입니다.
주요 위젯: AppBar, Column, Container, ElevatedButton

예시 코드 – Scaffold와 Column 사용:

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('기초 위젯 예제')),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            children: [
              Text('안녕하세요, Flutter!'),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: () => print('버튼 클릭'),
                child: Text('클릭'),
              ),
            ],
          ),
        ),
      ),
    ));

8. 입력 (Input)

사용자로부터 텍스트나 기타 입력을 받을 때 사용하는 위젯입니다.
주요 위젯: TextField, Form, FormField, Autocomplete

예시 코드 – TextField와 컨트롤러 사용:

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(home: InputExample()));

class InputExample extends StatefulWidget {
  @override
  _InputExampleState createState() => _InputExampleState();
}

class _InputExampleState extends State<InputExample> {
  final TextEditingController _controller = TextEditingController();

  void _printInput() {
    print('입력된 텍스트: ${_controller.text}');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('입력 예제')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(
              controller: _controller,
              decoration: InputDecoration(
                labelText: '텍스트 입력',
                border: OutlineInputBorder(),
              ),
            ),
            SizedBox(height: 16),
            ElevatedButton(
              onPressed: _printInput,
              child: Text('출력'),
            ),
          ],
        ),
      ),
    );
  }
}

9. 상호작용 모델 (Interaction Models)

사용자의 터치, 제스처, 드래그 등 상호작용을 처리하고 화면 전환을 위한 위젯입니다.
주요 위젯: GestureDetector, Dismissible, Draggable, Navigator, Hero

예시 코드 – GestureDetector 사용 예:

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(home: InteractionExample()));

class InteractionExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('상호작용 예제')),
      body: Center(
        child: GestureDetector(
          onTap: () => print('컨테이너를 탭했습니다.'),
          child: Container(
            padding: EdgeInsets.all(24),
            color: Colors.lightGreen,
            child: Text('탭하세요'),
          ),
        ),
      ),
    );
  }
}

10. 레이아웃 (Layout)

위젯을 배열하고 배치하는 데 사용되는 레이아웃 위젯들입니다.

  • 단일 자식 레이아웃:
    Align, AspectRatio, Container, SizedBox 등
  • 다중 자식 레이아웃:
    Column, Row, ListView, GridView, Stack 등
  • Sliver 위젯:
    CustomScrollView, SliverAppBar, SliverList 등

예시 코드 – Column과 Row를 활용한 간단한 레이아웃:

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('레이아웃 예제')),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            children: [
              Row(
                children: [
                  Expanded(child: Container(height: 50, color: Colors.red)),
                  SizedBox(width: 10),
                  Expanded(child: Container(height: 50, color: Colors.blue)),
                ],
              ),
              SizedBox(height: 20),
              Expanded(
                child: ListView.builder(
                  itemCount: 10,
                  itemBuilder: (context, index) => ListTile(
                    title: Text('리스트 항목 ${index + 1}'),
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    ));

11. 페인팅 및 효과 (Painting and Effects)

자식 위젯 위에 다양한 시각적 효과(클립, 투명도, 변환 등)를 적용할 때 사용됩니다.
주요 위젯: BackdropFilter, ClipOval, ClipPath, Opacity, Transform, CustomPaint

예시 코드 – Opacity와 Transform 사용:

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('페인팅 및 효과 예제')),
        body: Center(
          child: Transform.rotate(
            angle: 0.2,
            child: Opacity(
              opacity: 0.6,
              child: Container(
                width: 150,
                height: 150,
                color: Colors.purple,
                child: Center(child: Text('반투명 & 회전')),
              ),
            ),
          ),
        ),
      ),
    ));

12. 스크롤 (Scrolling)

스크롤 가능한 리스트나 그리드, 커스텀 스크롤뷰 등을 구현할 때 사용하는 위젯입니다.
주요 위젯: ListView, GridView, CustomScrollView, PageView, RefreshIndicator

예시 코드 – ListView 사용 예:

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('스크롤 예제')),
        body: ListView.builder(
          padding: EdgeInsets.all(16),
          itemCount: 20,
          itemBuilder: (context, index) => Card(
            child: ListTile(
              title: Text('항목 ${index + 1}'),
            ),
          ),
        ),
      ),
    ));

13. 스타일링 (Styling)

앱의 테마, 반응형 디자인, 여백 등을 관리하는 스타일 관련 위젯입니다.
주요 위젯: MediaQuery, Padding, Theme

예시 코드 – Padding과 Theme 적용 예:

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.teal,
      ),
      home: Scaffold(
        appBar: AppBar(title: Text('스타일링 예제')),
        body: Padding(
          padding: const EdgeInsets.all(24.0),
          child: Center(child: Text('패딩 적용 예제')),
        ),
      ),
    ));

14. 텍스트 (Text)

텍스트를 화면에 표시하고 다양한 스타일 및 서식을 적용할 때 사용합니다.
주요 위젯: Text, RichText, DefaultTextStyle

예시 코드 – Text와 RichText 사용 예:

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('텍스트 예제')),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                '단순 텍스트 예제',
                style: TextStyle(fontSize: 20, color: Colors.black),
              ),
              SizedBox(height: 20),
              RichText(
                text: TextSpan(
                  text: 'Rich',
                  style: TextStyle(fontSize: 20, color: Colors.blue),
                  children: [
                    TextSpan(
                        text: 'Text',
                        style: TextStyle(
                            fontWeight: FontWeight.bold, color: Colors.red)),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    ));