flutter出来这么久了, 还有小伙伴不明白状态管理的作用, 下面通过一个简单的例子来说明一下
先看效果:
状态管理切换用户信息具体实现:
1、创建用户模型
class UserModel{
String id;
String userId = "";
String name = "";
String nickName = "";
String age = "";
String sex = "";
String like = "";
String head = "";
UserModel(this.id, this.userId, this.name, this.nickName, this.age, this.like, this.sex, this.head);
}
2、创建状态管理类
class UserProviderModel with ChangeNotifier, DiagnosticableTreeMixin {
UserModel usermodel;
UserProviderModel(this.usermodel);
// get set
UserModel get user => usermodel;
set user(UserModel value) {
user = value;
notifyListeners();
}
// 更更新用户信息
void changUserInfo({required UserModel userInfo}){
usermodel = userInfo;
notifyListeners();
}
}
3、全局引入要管理的内容
void main() {
runApp(MultiProvider(providers: [
// 全局状态管理
ChangeNotifierProvider(
create: (_) => UserProviderModel(UserModel(
"820002",
"820002",
"无名之辈-二丫",
"nickName",
"14",
"复仇",
"女",
"https://nulujia.oss-cn-beijing.aliyuncs.com/image/%E6%88%AA%E5%B1%8F2022-09-15%2011.01.45.png")))
], child: const MyApp()));
}
4、通过Consumer展示用户信息
5、编辑用户信息
6、用户信息更新完毕
网友评论