Search code examples
flutterfutureprovider

Flutter : How save data comes from database (Future) in a list in provider


I have a service where I am receiving some data from API :

import '../models/clubs.dart';
import 'package:http/http.dart' as http;

class ApiService {
  var url = 'http://10.0.2.2:8000/api/v1/';

  getActiveSeasonClubs() async {
    var newurl = Uri.parse(url + 'active_season_clubs/');
    var response = await http.get(newurl);
    var data = clubsFromJson((response.body));
    return data;
  }
}

I want to make a copy of this list of data in provider to use it and update it in the app ,I used this but null data recieved :

class TeamsProvider with ChangeNotifier {
  var _clubs = [];
  get clubs => loadValue();
  Future loadValue() async {
    _clubs = await ApiService().getActiveSeasonClubs();
    return _clubs;
  }
}

and used it in FutureBuilder :

body: Consumer<TeamsProvider>(builder: (context, teamsProv, child) {
          return FutureBuilder(
              future: teamsProv.clubs,

Solution

  • Make these modifications:

    class TeamsProvider with ChangeNotifier {
      var _clubs = [];
      get clubs => _clubs;
      Future loadValue() async {
        _clubs = await ApiService().getActiveSeasonClubs();
        return _clubs;
      }
    }
    

    In your future builder use future: teamsProv.loadValue(). When you want to read the list, use teamsProv.clubs.

    If you want to modify this list form outside your provider class, create another void function there, that takes the changes as parameters, and uses them to modify _clubs from outside the class.