【发布时间】:2025-12-23 16:20:13
【问题描述】:
在我通过 API 修补信息后,我的 UI 似乎没有更新更改。我使用Provider 进行状态管理。代码如下:
用户模型:
class UserData extends ChangeNotifier {
String name,
surname,
birthDate;
UserData({
this.generalEmail,
this.surname,
this.primaryPhone,
});
UserData.fromJson(Map<String, dynamic> json) {
name= json['name'];
surname = json['surname'];
birthDate= json['birthDate'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = Map<String, dynamic>();
data['name'] = this.name;
data['surname'] = this.surname;
data['birthDate'] = this.birthDate;
return data;
}
}
用户商店:
class UserStore extends ChangeNotifier {
Map<String, UserData> _userInfo = {};
Map<String, UserData> get userInfo => _userInfo ;
void updateUserInfo(UserData user) {
_userInfo[user.userId] = user;
notifyListeners();
}
UserData getUserInfoByUserId(String userId) => _userInfo[userId];
}
以及用户存储的服务操作:
UserStore userStore;
BuildContext context;
UserActions(BuildContext context) {
this.context = context;
this.userStore = Provider.of<UserStore>(context, listen: false);
}
Future<UserData> patchUserInfo(
String name,
surname, birthDate,) async {
final response = await apiRequest(Method.PATCH, '/users',
body: jsonEncode({
"name": name,
"surname": surname,
"birthDate": birthDate,
}));
Map<String, dynamic> jsonDecodedResponse = jsonDecode(response.body);
return UserData(
name: jsonDecodedResponse['name'],
surname: jsonDecodedResponse['surname'],
birthDate: jsonDecodedResponse['birthDate'],
);
}
Future<void> changeUserInfo(
String name,
surname,
birthDate) async {
final userRes = await patchUserInfo( // call the API and pass the data
name,
surname,
birthDate,);
if (userRes != null) {
userStore.updateUserInfo(userRes);
return;
}
userStore.updateUserInfo(userRes);
}
未更新的用户界面:
final userStore = Provider.of<UserStore>(context, listen: false);
UserData user = userStore.getUserInfo(userId);
...
return Column(
children: [
Text(user.name), // only updates it when I refresh the widget
Text(user.surname), // only updates it when I refresh the widget
Text(user.birthDate), // only updates it when I refresh the widget
],
);
API 通过后,我想用最新的更改更新我的 UI,如果没有,请不要更新 UI。我不确定,但我可能没有正确设置 UserStore 中的 updateUserInfo 方法,以便在成功调用 API 后立即更新 UI。我的错误在哪里?当它是一个列表时我可以使用indexWhere,但是当数据模型是Map 时我如何更新它,就像我在UserStore 中定义的那样?
提前感谢您的帮助!
【问题讨论】:
标签: flutter mobile flutter-provider