import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
void main() {
runApp(ProviderScope(child: MyApp()));
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
print("HomePage build");
return Scaffold(
body: SafeArea(
child: Column(
children: [
Expanded(child: Top1()),
Expanded(child: Top2()),
Expanded(child: Bottom()),
],
),
),
);
}
}
class Top1 extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
print("Top 1 build");
int num = ref.watch(numProvider);
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text("Top 1", style: TextStyle(fontSize: 40, fontWeight: FontWeight.bold)),
Text("num : ${num}", style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold))
],
),
);
}
}
class Top2 extends ConsumerWidget {
const Top2({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
print("Top 2 build");
NumVM vm = ref.read(numProvider.notifier);
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Top 2", style: TextStyle(fontSize: 40, fontWeight: FontWeight.bold)),
ElevatedButton(onPressed: (){
vm.increase();
}, child: Icon(Icons.add))
],
),
);
}
}
class Bottom extends StatelessWidget {
const Bottom({
super.key,
});
@override
Widget build(BuildContext context) {
print("Bottom build");
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Bottom", style: TextStyle(fontSize: 40, fontWeight: FontWeight.bold)),
],
),
);
}
}
// 프로바이더 (창고 관리자)
final numProvider = StateNotifierProvider<NumVM, int>((ref) {
return NumVM(1);
});
// 뷰모델 (창고)
class NumVM extends StateNotifier<int> {
NumVM(super.state);
void increase() {
state++;
}
}