Home > OS >  Unable to fix instance of classname error
Unable to fix instance of classname error

Time:07-27

I am trying to read a local json file so I wrote this code below.The problem is when i run this code I am getting this error

Instance of 'Cities'

I have added toString method as suggested But nothing changes.Problem persists.Thanks in advance

Future<void> getJson()async{
  await  DefaultAssetBundle.of(context).loadString("assets/jsondata/cities.json").then((value) {

     var list=jsonDecode(value);
     for(var val in list){
       Cities city=Cities.fromJson(val);
       alCities.add(city);

     }
     print(alCities);

  });
}

  @override
  Widget build(BuildContext context) {
      getJson();

This is my model class

class Cities {
  late String id;
  late String name;
  late String latitude;
  late  String longitude;
  late  String population;
  late String region;

  Cities(
      {required this.id,
        required this.name,
        required this.latitude,
        required this.longitude,
        required this.population,
        required this.region});

  Cities.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    latitude = json['latitude'];
    longitude = json['longitude'];
    population = json['population'];
    region = json['region'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['name'] = this.name;
    data['latitude'] = this.latitude;
    data['longitude'] = this.longitude;
    data['population'] = this.population;
    data['region'] = this.region;
    return data;
  }

  @override
  String toString() {
    return 'Cities{id: $id, name: $name, latitude: $latitude, longitude: $longitude, population: $population, region: $region}';
  }
}

CodePudding user response:

May u have to change print(alCities); To print(Cities);

CodePudding user response:

Instance of 'Cities' is not an error.

To print the content of city you have to use the .tojson which you already created.

for(city in alCities)
{
  print(city.toJson());
}
  • Related