Updating State with Provider after API call


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(
        Provider.of<UserStore>(context, listen: false)

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) {

  addUser(User list) {

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

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.


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

   void deleteUser(User list) {

   void addClient(User list) {

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

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 *