Riverpod hooks_riverpod 入門
Jun 14, 2022
- 安裝
environment:
sdk: ">=2.12.0 <3.0.0"
flutter: ">=2.0.0"
dependencies:
flutter:
sdk: flutter
flutter_hooks: ^0.18.0
hooks_riverpod: ^2.0.0-dev.9
2. Hello World
// 宣告全域 provider
final helloworldProvider = Provider((_)=>"Hello world");// 入口
void main() {
runApp(
// 為了讓widgets可以讀取providers,需要用ProviderScope將application包起來 ProviderScope(
child: MyApp(),
),
);
}//
class MyApp extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final String value = ref.watch(helloWorldProvider);
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Example')),
body: Center(
child: Text(value),
),
),
);
}
}
ref 的使用:監聽另一個provider
// 新增Provider
final stateProvider = StateProvider<int>((ref)=>0);// 修改helloworldProvider 監聽 stateProvider的變化
final helloworldProvider = Provider((ref) => ref.watch(stateProvider));···
// 新增漂浮按鈕
floatingActionButton: FloatingActionButton(
onPressed: (){
ref.read(stateProvider.notifier).state++;
},
child: Icon(Icons.add),),
關鍵字
Provider、StateProvider、ProviderScope、ref.read、ref.watch、notifier