Home > OS >  Unhandled Exception: type '_CompactLinkedHashSet<(dynamic) => Map<String, dynamic>&
Unhandled Exception: type '_CompactLinkedHashSet<(dynamic) => Map<String, dynamic>&

Time:01-21

I am trying to get a JSON response from this server. I am new to flutter and I'm confused about how to get it done. can anybody point out what I did wrong???

class RESTAPIService{
  String apiUrl = "https://mocki.io/v1/048e68cc-9ddb-4aca-8264-6e9f8f273fd2";
  Future<List<User>> getUsers() async{
    final response = await http.get(Uri.parse(apiUrl));
    print(response.body);
    if(response.statusCode == 200){
      throw getUsersList(response.body);
    }else{
      throw Exception("Couldn't fetch data");
    }
  }
  List<User> getUsersList(String responseBody){
    final parsebody = json.decode(responseBody).cast<Map<String, dynamic>>();
    return parsebody.map<User>({(json) => User(name: "", city: "", image: "").fromJson(json)}).toList();
  }
}

I did my conversions like bellow.

class User{
  String name;
  String city;
  String image;
  User({required this.name, required this.city, required this.image});

  Map<String, dynamic> fromJson(Map<String, dynamic> json){
    name = json['name'];
    city = json['city'];
    image = json['image'];
    return json;
  }
  Map<String, dynamic> toJson(){
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['name'] = this.name;
    data['city'] = this.city;
    data['image'] = this.image;
    return data;
  }
}

I called the json data here. When the app runs it only shows "Loading..." and won't show the json response. But I do get the json response from the server. it just doesn't show in my app UI.

child: FutureBuilder(
                  future: apiService.getUsers(),
                  builder: (context, snapShot){
                    if(snapShot.hasData){
                      return ListView.builder(
                          itemCount: snapShot.data!.length,
                          itemBuilder: (context, index){
                            return InkWell(
                              onTap: (){
                              },
                              child: Container(
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(10),
                                  boxShadow: [
                                    BoxShadow(
                                      blurRadius: 3, spreadRadius: 3,
                                      color: Colors.grey.withOpacity(0.3),
                                    )
                                  ]
                                ),
                                margin: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
                                padding: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
                                child: ListTile(
                                  title: Text(snapShot.data![index].name ?? '', style: TextStyle(
                                    fontSize: 18, color: Colors.black,
                                  ),),
                                  subtitle: Text(snapShot.data![index].city ?? '', style: TextStyle(
                                    fontSize: 15, color: Colors.black,
                                  ),),
                                  leading: ClipOval(
                                    child: Image.network(snapShot.data![index].image, fit: BoxFit.cover, width: 60, height: 60,),
                                  ),
                                ),
                              ),
                            );
                          }
                      );
                    }else{
                      return Container(
                        child: Center(
                          child: Text("Loading...", style: TextStyle(
                            color: Colors.black, fontSize: 15,
                          )),
                        ),
                      );
                    }
                  },
                ),`

CodePudding user response:

Your response is list,

So it should be

List<User> getUsersList(String responseBody) {
  final parsebody = json.decode(responseBody) as List?;
  return (parsebody?.map((e) => User.fromMap(e)))?.toList() ?? [];
}

Try using factory model like

class User {
  String name;
  String city;
  String image;
  User({required this.name, required this.city, required this.image});

  Map<String, dynamic> toMap() {
    final result = <String, dynamic>{};

    result.addAll({'name': name});
    result.addAll({'city': city});
    result.addAll({'image': image});

    return result;
  }

  factory User.fromMap(Map<String, dynamic> map) {
    return User(
      name: map['name'] ?? '',
      city: map['city'] ?? '',
      image: map['image'] ?? '',
    );
  }

  String toJson() => json.encode(toMap());

  factory User.fromJson(String source) => User.fromMap(json.decode(source));
}
  • Related