반응형
Riverpod을 실전처럼 연습하기 위해 간단한 프로젝트를 만들어보는 게 좋겠어요.
예를 들어, 할 일 관리 앱을 구현하면서 아래의 기능들을 연습할 수 있습니다:
1. Provider를 이용한 상태 관리: 할 일 목록을 StateNotifier로 관리.
2. 상태 필터링: 완료된 할 일과 미완료된 할 일을 필터링해서 보여주기.
3. UI와 Riverpod 연결: 상태 변경 시 UI가 자동으로 업데이트되도록 구성.
이제 간단한 예제를 보여드릴게요:
기본 설정
pubspec.yaml에 Riverpod 추가:
dependencies:
flutter_riverpod: ^2.0.0
상태 모델 정의
// 1. 데이터 모델 정의
// 할 일 데이터를 나타내는 클래스. id, title, 완료 여부를 포함.
class Todo {
final String id; // 할 일의 고유 ID
final String title; // 할 일 제목
final bool isCompleted; // 완료 여부
Todo({
required this.id,
required this.title,
this.isCompleted = false,
});
// 완료 상태를 토글하는 메서드 (완료 ↔ 미완료)
Todo toggleCompleted() {
return Todo(
id: id,
title: title,
isCompleted: !isCompleted,
);
}
}
// 2. 상태 관리용 StateNotifier 정의
// 할 일 리스트를 관리하며, 상태 변경 시 UI에 알림.
class TodoNotifier extends StateNotifier<List<Todo>> {
TodoNotifier() : super([]); // 초기 상태는 빈 리스트
// (2-1) 새로운 할 일을 추가
void addTodo(String title) {
final newTodo = Todo(
id: DateTime.now().toString(), // 고유 ID로 현재 시간을 사용
title: title,
);
state = [...state, newTodo]; // 새로운 할 일을 기존 리스트에 추가
}
// (2-2) 특정 할 일의 완료 상태를 토글
void toggleTodo(String id) {
state = state
.map((todo) => todo.id == id ? todo.toggleCompleted() : todo)
.toList();
}
// (2-3) 특정 할 일을 삭제
void removeTodo(String id) {
state = state.where((todo) => todo.id != id).toList();
}
}
// 3. Provider 정의
// TodoNotifier를 관리하는 Riverpod의 StateNotifierProvider
final todoProvider =
StateNotifierProvider<TodoNotifier, List<Todo>>((ref) => TodoNotifier());
UI 연결
// 4. UI 구성
// 할 일 리스트와 추가/수정/삭제 기능을 보여주는 UI
class TodoApp extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
// (4-1) 상태 읽기: 현재 할 일 리스트를 구독
final todos = ref.watch(todoProvider);
return Scaffold(
appBar: AppBar(title: Text("Todo App with Riverpod")),
body: ListView.builder(
// (4-2) 상태를 기반으로 할 일 리스트 렌더링
itemCount: todos.length,
itemBuilder: (context, index) {
final todo = todos[index];
return ListTile(
title: Text(
todo.title,
// (4-3) 완료된 항목은 텍스트에 취소선을 추가
style: TextStyle(
decoration: todo.isCompleted
? TextDecoration.lineThrough
: TextDecoration.none,
),
),
// (4-4) 완료 상태를 토글하는 버튼
trailing: IconButton(
icon: Icon(todo.isCompleted
? Icons.check_box
: Icons.check_box_outline_blank),
onPressed: () => ref.read(todoProvider.notifier).toggleTodo(todo.id),
),
// (4-5) 항목을 길게 누르면 삭제
onLongPress: () =>
ref.read(todoProvider.notifier).removeTodo(todo.id),
);
},
),
// (4-6) 할 일 추가를 위한 FloatingActionButton
floatingActionButton: FloatingActionButton(
onPressed: () async {
// (4-6-1) 사용자 입력을 받기 위한 다이얼로그 표시
final title = await showDialog<String>(
context: context,
builder: (context) {
String input = ''; // 입력값을 저장
return AlertDialog(
title: Text("Add Todo"),
content: TextField(
onChanged: (value) => input = value, // 입력값을 실시간으로 업데이트
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(), // 다이얼로그 닫기
child: Text("Cancel"),
),
TextButton(
onPressed: () => Navigator.of(context).pop(input), // 입력값 반환
child: Text("Add"),
),
],
);
},
);
// (4-6-2) 입력값이 비어있지 않을 경우 상태 업데이트
if (title != null && title.isNotEmpty) {
ref.read(todoProvider.notifier).addTodo(title);
}
},
child: Icon(Icons.add),
),
);
}
}
// 5. 앱 실행
// ProviderScope는 Riverpod의 상태 관리 범위를 정의
void main() {
runApp(ProviderScope(child: MaterialApp(home: TodoApp())));
}
연습 포인트
1. 데이터 추가/수정/삭제: addTodo, toggleTodo, removeTodo 메서드 활용.
2. 상태 변화 추적: Riverpod의 ConsumerWidget과 watch로 상태 변화 관찰.
3. 추가 기능: 필터링(예: 완료된 것만 보기) 또는 로컬 스토리지 연결.
이 코드를 기반으로 확장해 보면서 연습해 보면 좋아요! 추가로 궁금한 점이 있으면 언제든 물어보세요. 😊
반응형
'IT > flutter' 카테고리의 다른 글
[디자인패턴] Flutter에서 MVVM 패턴 적용하기: 개념부터 예제코드까지 (0) | 2025.01.29 |
---|---|
[flutter] Container위젯과 DecoratedBox 위젯의 효율적인 사용 (0) | 2025.01.23 |
[상태관리] Riverpod - StateNotifier와 StateNotifierProvider (0) | 2024.12.19 |
[상태관리] Riverpod - FutureProvider 비동기 데이터 관리 (0) | 2024.12.19 |
[상태관리]Riverpod의 WidgetRef 객체 (0) | 2024.12.19 |