Flutter : How to add more json data to existing Model Class?

Viewed 87

I have a scenario where the following function is called again and again whenever the user hits the "Load More" button.

The problem I'm facing is, that it replaces previously loaded data with a new one. Instead, it should add to the bottom of the Listview.Builder

Future fetchData() async{
  var url = "url_goes_here";
  final response = await http.get(url);
    if (response.statusCode == 200) {
       var resBody = jsonDecode(response.body);
       var data = resBody['data'] as List;
       if (data.isNotEmpty) {
          setState(() {           

            listVariable = data
                .map<ModelClass>((json) => ModelClass.fromJson(json))
                .toList();         

          });
        }
    }

}
3 Answers
   List<ModelClass> listVariable =List<ModelClass>(); //describe the object that way.

--------and---------

      data.map<ModelClass>((json) {
             listVariable.add(ModelClass.fromJson(jsonn));
               } )).toList();         

You should add received data to your listVariable, not assign a new value. Try this code:

  final listVariable = <ModelClass>[];

  ...

  Future fetchData() async {
    var url = "url_goes_here";
    final response = await http.get(url);
    if (response.statusCode == 200) {
      var resBody = jsonDecode(response.body);
      var data = resBody['data'] as List;
      if (data.isNotEmpty) {
        final list = data.map<ModelClass>((json) => ModelClass.fromJson(json));
        setState(() {
          listVariable.addAll(list);  // HERE: addAll() instead of assignment
        });
      }
    }
  }

I was able to figure out answer myself.

setState(() {           

            listVariable.addAll(data
                .map<ModelClass>((json) => ModelClass.fromJson(json))
                .toList();         

          }));

@Mol0ko and @hasan karaman both are right but @Mol0ko Makes better sense when you have a set of data to addAll to existing data.

Related