((ref) { return NumVM(1); }); // 뷰모델 (창고"> ((ref) { return NumVM(1); }); // 뷰모델 (창고"> ((ref) { return NumVM(1); }); // 뷰모델 (창고">
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
void main() {
// riverpod 세팅
runApp(ProviderScope(child: MyApp()));
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends ConsumerWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
int num = ref.watch(numProvider); // read or watch는 state에 접근가능!!
return Scaffold(
body: Center(child: Text("$num", style: TextStyle(fontSize: 30))),
floatingActionButton: FloatingActionButton(
onPressed: () {
NumVM vm = ref.read(numProvider.notifier); // 창고에 접근가능
vm.increase();
},
child: Icon(Icons.add),
),
);
}
}
// 프로바이더 (창고 관리자)
final numProvider = StateNotifierProvider<NumVM, int>((ref) {
return NumVM(1);
});
// 뷰모델 (창고)
class NumVM extends StateNotifier<int> {
NumVM(super.state);
void increase() {
state++;
}
}