skip to Main Content

This is my JSON:

{
'malls' : [{'id':1 , 'name': 'salam'},{'id':2 , 'name': 'salam2'}]
}

And this is my modeling JSON classes:

class MALL {
  final int id;
  final String name;

  MALL({required this.id, required this.name});

  factory MALL.fromJson(Map<String, dynamic> data) {
    return MALL(id: data['id'], name: data['name']);
  }
}

class City {
  final List<MALL> malls;

  City({required this.malls});
  factory City.fromJson(Map<String, dynamic> data) {
    var list = data['malls'] as List;
    List<MALL> mallList = list.map((i) => MALL.fromJson(i)).toList();
    return City(malls: mallList);
  }
}

This is my get method:

Future<List<MALL>> get() async {
  var response = await http.get(Uri.parse(URL), headers: {"authorization": "Bearer ${token}", "Content-Type": "application/json"});
  var data = jsonDecode(response.body);
  City api = City.fromJson(data);
  return data['malls'];
}

I get this output:

[Instance of 'MALL', Instance of 'MALL']

I want my JSON in output by I got the instance of my classes.
How can I convert the instances to my data? It means I want to return my JSON in output and I can access the keys of malls in my FutureBuilder.

2

Answers


  1. If you wanna print the response of a Class you can override the toString method to print the response of the Class. Example:

    class MALL {
      final int id;
      final String name;
    
      MALL({required this.id, required this.name});
    
      factory MALL.fromJson(Map<String, dynamic> data) {
        return MALL(id: data['id'], name: data['name']);
      }
      
      @override
      String toString() => "{ id : $id, name : $name}";
    }
    

    Now you will see the result in console.

    Login or Signup to reply.
  2. Inside your FutureBuilder yo will get list of Malls. Thats you have to use loop or list view builder to access those elemet.

    if you want to print the list data. you have to print first element

    inside your future build when data is loded.

    print(data.first.toString())
    

    add this line of code inside your malls calss

    @override
    String toString() => "{ id : $id, name : $name}";
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search