Ad

Add An Another Attribute To An Existing List In Flutter

- 1 answer

I have been trying many ways to add an isChecked: false attribute to every list inside the _filterOptions List in my Flutter Project. I couldn't find any solution to this. If there is any solution I am happy to see it.

List<dynamic> _filters = [];
List<List<dynamic>> _filterOptions =[];
var filters =
    await json.decode(data)["getProductsByStore"]["aggregations"];
    for(int i = 0; i < filters.length; i++){
      _filters.add(filters[i]["label"]);
      _filterOptions.add(filters[i]["options"]);

    }
    //print(filters[0]["options"]);
    //print(_filters);
    print(_filterOptions);

I am getting this kind of nested list when printed and I want to add the attribute to every list. enter image description here

as an example: [[{count: 3, label: 30-40, value: 30_40, isChecked:false}], [{count: 2, label: Bagged , value: 50, isChecked:false},{...},{...}...]]

Ad

Answer

Create Model class with your data and bool isChecked

class ModelClass{
  String? label;
  int? count;
  List? options;
  bool? isChecked;

  ModelClass({this.label, this.count , this.options, this.isChecked = false});

  ModelClass.fromJson(Map<String, dynamic> json){
    label = json['label'];
    count = json['count'];
    options = json['options'];
  }

}

then you can add data like below code

 List<ModelClass> list = [];

  void function()async{
    List<dynamic> _filters = [];
    List<List<dynamic>?> _filterOptions =[];
    var filters =
        await json.decode(data)["getProductsByStore"]["aggregations"];
    for(int i = 0; i < filters.length; i++){
      ModelClass modelClass = ModelClass.fromJson(filters[i]);
      list.add(modelClass);

      _filters.add(modelClass.label);
      _filterOptions.add(modelClass.options);

    }
    print(list[0].options);
    print(list[0].isChecked);

  }

if you want to modify isChecked for some specific index

list[0].isChecked = false;
Ad
source: stackoverflow.com
Ad