Search code examples
flutterflutter-provider

How to update a Future via Provider


I define a Future: late Future snapshot;

I initialize it when a button is pressed: setState(() => snapshot = loadData(...))

I have a FutureBuilder to use the future.

On the other hand, I have a button which updates a value in a ChangeNotifier (from Provider) when pressed. I would like to change my Future called 'snapshot', with this new value as a parameter of loadData(), and rebuild UI. Any idea to do it ?


Solution

  • Sorry but, First of all, your logic is somehow wrong because you don't need FutureBuilder to initialize snapshot. Secondly you need to define a nullable variable which is named snapshot like this:dynamic snapshot, and you don't need to define variables as future otherwise you can not use them.Then you need a function inside the provider to request Api. Example:

    class SomeProvider with ChangeNotifier{
    dynamic snapshot;
    
    getSnapshots()async{
    final res = await Dio().get("https://jsonplaceholder/posts");
    snapshot = res.data;
    notifyListeners();
    }
    

    You can use this function inside onPressed function of button and use snapshot in somewhere).