【问题标题】:Not updating state with provider after patch/update, Flutter补丁/更新后不与提供者更新状态,颤振
【发布时间】: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


    【解决方案1】:

    您没有听到 Provider 中的更改(请参阅:listen: false)。您可以使用以下代码在您使用updateUserInfo 进行更改时收到通知:

    return Consumer<UserStore>(builder: (context, UserStore userStore, child) {
      UserData user = userStore.getUserInfo(userId);
      return Column(
        children: [
          Text(user.name),
          Text(user.surname), 
          Text(user.birthDate),
        ],
      );
    });
    

    当你从 API 获取数据时使用这个(因为这里你不需要监听):

    context.read<UserStore>().updateUserInfo(userRes);
    

    Consumer上方创建一个像这样的提供者:

    return ChangeNotifierProvider(create: (context) => UserStore(), child: ...);
    

    【讨论】:

    • 我尝试了您的解决方案,但我的 UI 仍未更新。当我想更新用户信息并将编辑后的数据作为 UserData 的对象传递时,我的 updateUserInfo 方法好吗?
    • 我没有看到任何问题,但是如果您可以用完整的代码更新您的问题,我可以看看它。
    • 已更新,如有其他需要,请告诉我。谢谢!
    • UserStore 也是提供者吗?我没有看到声明以及如何创建此提供程序。无论如何,不​​要使用extends ChangeNotifier,而是使用with ChangeNotifier。我看不出将UserData 设为ChangeNotifier 的意义,因为它不会通知任何听众。我的提示是,您没有正确创建 UserStore 作为提供者。
    • 更新了 UserStore 类。将尝试with ChangeNotifier