RiverPod
导入和基础等查看官方文档
import 'package:hooks_riverpod/hooks_riverpod.dart';
final normalProvider = Provider<String>((ref) {
return "this is normalProvider";
});
final stateProvider = StateProvider.autoDispose((ref) {
return "this is stateProvider";
});
void test(WidgetRef ref) {
//https://www.wodecun.com/blog/8264.html
//autoDispose family(传递参数)
//八大Provider 实际基本使用注解形式
//1.Provider 普通provider
var normal = ref.read(normalProvider);
//2.stateProvider
var state = ref.read(stateProvider.notifier).state;
print("back=$state");
state = "this is stateProvider change";
print("back=$state");
//3.StateNotifierProvider
//4.FutureProvider
//5.StreamProvider
//6.ChangeNotifierProvider
//7.NotifierProvider
//8.AsyncNotifierProvider
String a;
}
实际项目中更多使用注解形式创建provider
插件
vscode 可以使用Flutter Snippets Flutter Riverpod Snippets 等辅助快捷生层代码
flutter_hooks
一般Riverpod都会配合flutter_hooks使用进行项目的一个状态管理
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
class TestHookExample extends HookConsumerWidget {
const TestHookExample({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
useEffect(() {
//执行初始化代码 类似initState效果
return () {
//类似dispose 效果
};
}, []); //参数为空list 表示只执行一次 有参数表示参数变动时也会执行
final txt = useState('');
final txtCtroll = useTextEditingController(text: "default value");
//还有其他各种use hooks 参见官方文档
return Container();
}
}
github地址
参考文档
https://www.wodecun.com/blog/8264.html