🍟 main.dart – 맥도날드 비유 Counter 예제
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
// 🍔 점원 (상태를 관리하고 번호를 바꾸는 역할)
class CounterNotifier extends StateNotifier<int> {
CounterNotifier() : super(0); // 초기 번호는 0 (아직 주문 안 들어옴)
void increment() {
state++; // 🍟 점원이 번호표 하나 증가시킴 (다음 손님 호출)
}
}
// 🍟 번호표 (손님이 이걸 계속 지켜보고 있음)
final counterProvider = StateNotifierProvider<CounterNotifier, int>((ref) {
return CounterNotifier(); // 🍔 점원 채용
});
void main() {
runApp(
// 🏢 맥도날드 매장 오픈 (ProviderScope로 시스템 구성)
ProviderScope(child: MyApp()),
);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: '맥도날드 비유 Counter',
home: CounterScreen(),
);
}
}
// 🍔 손님 (UI) - 전광판을 보며 자신의 번호가 언제 불리는지 확인
class CounterScreen extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final counter = ref.watch(counterProvider); // 🍟 전광판 보는 중 (번호표 지켜봄)
return Scaffold(
appBar: AppBar(title: Text('🍔 맥도날드 Counter')),
body: Center(
child: Text(
'현재 호출된 번호: \$counter', // 📺 전광판 출력
style: TextStyle(fontSize: 24),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
// 🍔 점원에게 "번호 올려줘!" 라고 요청 (버튼 클릭)
ref.read(counterProvider.notifier).increment();
},
child: Icon(Icons.add),
),
);
}
}
🧠 비유 정리 매핑
코드 역할 | 비유 | 설명 |
---|---|---|
StateNotifier |
점원 | 상태(번호표)를 직접 수정하는 사람 |
StateNotifierProvider |
번호표 | 손님(Widget)이 지켜보는 상태 |
ConsumerWidget |
손님 | 전광판을 지켜보며, 번호가 자기 번호되면 반응 |
ref.watch(...) |
전광판 보기 | 상태가 바뀌면 자동으로 UI 갱신 |
ref.read(...).increment() |
점원에게 요청 | 번호 하나 더 호출 (상태 변경) |
ProviderScope |
맥도날드 매장 전체 | Provider 시스템의 시작점 |
'전체보기' 카테고리의 다른 글
박혜수 디어엠, 2025년 드디어 첫 방송! 청춘 로맨스의 귀환 (0) | 2025.04.15 |
---|---|
2025년 화제작! 고민시 셰프 변신 드라마 ‘당신의 맛’ 방송 전 미리보기 (0) | 2025.04.15 |
선우 사과문 2025 총정리: 인성 논란부터 해명까지, 진짜 이유는? (2) | 2025.04.15 |
남성수술비용 2025년 최신 가이드|가격별 정리와 주의사항 (0) | 2025.04.15 |
민방위 사이버교육 2025 최신 가이드|신청부터 수료까지 한 번에! (0) | 2025.04.15 |