home_repository
// 통신 담당
class HomeRepository {
Future<int> fetchNumber() {
return Future.delayed(Duration(seconds: 3), ()=> 3);
}
}
home_page_vm
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:frapp/home_repository.dart';
// 뷰 모델 (창고)
class HomeVM extends StateNotifier<int?>{
HomeVM(super.state);
Future<void> notifyInit() async {
int num = await HomeRepository().fetchNumber(); // 3초
state = num;
}
}
// 뷰 모델 관리하는 관리자 (창고 관리자)
// watch하거나, read할때 실행됨 (View에서 실행시킴)
final homeProvider = StateNotifierProvider.autoDispose<HomeVM, int?>((ref) {
print("homeProvider가 HomeVM을 생성함");
return HomeVM(null)..notifyInit();
});
home_page
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:frapp/home_page_vm.dart';
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: HomeBody(),
);
}
}
class HomeBody extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
int? num = ref.watch(homeProvider);
if(num == null){
return Center(
child: CircularProgressIndicator(),
);
}else{
return Center(
child: Text("숫자 : $num"),
);
}
}
}
main
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:frapp/home_page.dart';
void main() {
runApp(ProviderScope(child: MyApp()));
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: HomePage(),
);
}
}