[flutter] 플러터 스택드 위젯에서 메모장 앱 만들기

플러터(Flutter)로 스택드(Stacked) 위젯을 활용하여 간단한 메모장 앱을 만들어보겠습니다. 스택드 위젯을 사용하면 화면을 여러 개의 위젯으로 쌓을 수 있어 레이아웃을 유연하게 조절할 수 있습니다. 본 예제에서는 메모를 추가하고 삭제할 수 있는 간단한 메모장 앱을 만들어보겠습니다.

1. 필수 패키지 설치

우선 플러터 플러그인을 설치하고 새로운 플러터 프로젝트를 생성합니다. 메모장 앱에 필요한 기본적인 기능을 제공하는 provider 패키지를 설치합니다.

dependencies:
  flutter:
    sdk: flutter
  provider: ^5.0.0

터미널에서 flutter pub get 명령어로 패키지를 설치합니다.

2. 메모 목록 화면 구현

메모 목록을 표시하는 화면을 구현합니다. ListView.builder를 사용하여 동적으로 메모를 표시하고, Stack 위젯을 사용하여 추가 버튼을 화면 오른쪽 아래에 고정시킵니다.

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:your_app_name/memo.dart';

class MemoListScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Memo List'),
      ),
      body: Consumer<Memo>(
        builder: (context, memo, child) {
          return ListView.builder(
            itemCount: memo.memoList.length,
            itemBuilder: (BuildContext context, int index) {
              return ListTile(
                title: Text(memo.memoList[index]),
                trailing: IconButton(
                  icon: Icon(Icons.delete),
                  onPressed: () {
                    memo.deleteMemo(index);
                  },
                ),
              );
            },
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {
          // add memo
        },
      ),
    );
  }
}

3. 메모 추가 기능 구현

메모를 추가하는 기능을 구현합니다. 다이얼로그를 통해 사용자로부터 메모 내용을 입력받고, Provider를 통해 메모를 추가합니다.

void _showAddMemoDialog(BuildContext context, Memo memo) {
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        title: Text('Add Memo'),
        content: TextField(
          controller: _textController,
        ),
        actions: <Widget>[
          TextButton(
            child: Text('Cancel'),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
          TextButton(
            child: Text('Add'),
            onPressed: () {
              memo.addMemo(_textController.text);
              Navigator.of(context).pop();
            },
          ),
        ],
      );
    },
  );
}

결론

위 예제를 통해 플러터의 스택드(Stacked) 위젯을 활용하여 간단한 메모장 앱을 만들어 보았습니다. 스택드 위젯을 사용하여 유연하고 다양한 레이아웃을 구성할 수 있으며, Provider를 통해 상태 관리를 간편하게 할 수 있습니다. 각 위젯의 상태를 유기적으로 연결해가는 과정을 경험할 수 있는 좋은 예제가 되었습니다.