Updating State with Provider after API call

Issue

How do I update the state with Provider after I’ve called the API to update it to the BE? I pass the arguments from one screen to another, then after I edit the text, I trigger the API call to the BE and I get the return value of the response and I want to update the state with that response with Provider. How is that possible? Here is the code:

Here I call the API and pass the arguments I’ve edited in my text fields:

onPressed: () async {
                  final updatedUser = await    await APICall.updateUser(
                          userID,
                          updateName,
                          updateEmail,
                        );
        Provider.of<UserStore>(context, listen: false)
                      .updateUser(updatedUser);
                      Navigator.pop(context);
                    },

Here is the API call where I return the response of the updated User:

Future<User> updateUser(String userID, String name, String email) async {
    final response =
        await APICalls.apiRequest(Method.PATCH, '/users', this._jsonWebToken,
            body: jsonEncode({
              "id": userID,
              "name": name,
              "email": email,
            }));
    Map<String, dynamic> jsonDecodedResponse = jsonDecode(response.body);
    return User(
        id: jsonDecodedResponse['data']['id'],
        name: jsonDecodedResponse['data']['name'],
        email: jsonDecodedResponse['data']['email'],
    );
  }

Now I wanted to pass that response I’ve got from the API call to pass it to the providers state:

deleteUser(User list) {
    _userList.remove(list);
    notifyListeners();
  }

  addUser(User list) {
    _userList.add(list);
    notifyListeners();
  }

updateUser(User ){//I'm not sure how do define the updateUser method...
   notifyListeners();
} 

The update works on the BE side, and on the FE only when I refresh the widget, not immediately after the response is returned, which is the way I want it to work.

Solution

class UserStore extends ChangeNotifier {
   List<User> clientList = [];

   void deleteUser(User list) {
      clientList.remove(list);
      notifyListeners();
   }

   void addClient(User list) {
      clientList.add(list);
      notifyListeners();
   }

   void updateUser(User user){
      clientList[clientList.indexWhere((element) => element.id == user.id)] = user;
      notifyListeners();
   } 
}

What you have to do now is to listen to this provider on your widget. When the user will be updated, the changes will be applied to any widget listening to the clientList.

Note I’ve changed the clientList variable to public, so it can be listened by any widget outside.

Answered By – Steve

Answer Checked By – David Marino (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *