Flutter/Dart – Use something like ChangeNotifier or setState within Future?

Issue

I’m using SocialProvider with ChangeNotifier. I want it to update its Consumer listener widgets once the user logs in and after posting to a database on the web.

Currently, I’m calling a Future method which inserts the new values to a Shared Preferences file upon a successful http post, but this won’t update the UI until a call is made to a page which loads shared preferences.

In order to see an instant update, is there any way to access something like the ChangeNotifier or other kind of setState type function from within a Future? Here’s the future;

Future<void> postSocialData(String email) async {
    final url = "http://example.com/example.php?currentemail=$email"          

  final response = await http.get(url);
  String currentuserid;

  if (response.statusCode == 200) {

    currentuserid =  response.body;

      setSharedPreferences(
      currentavatar: "http://example.com/" + response.body + "-user.jpg",
      currentemail: email,
      currentlogged: true,
      currentuserid: currentuserid,
    );

    print(response.body);

  } else {

    throw Exception('We were not able to successfully post social data.');
  }
}

Any ideas on how to get an instant update from a Future method?

Solution

Turns out I was able to insert the Future<void> postSocialData within the scope of the class SocialProvider with ChangeNotifier itself and hence use The ChangeNotifier within the Future to alert the Consumers/listeners.

Answered By – Meggy

Answer Checked By – Robin (FlutterFixes Admin)

Leave a Reply

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