skip to Main Content

Am a beginner in flutter development and am currently using dio for handling api calls. Currently the response is showing in the correct format after printing it. But in the parsing session I got error like this "type ‘List’ is not a subtype of type ‘Map<String, dynamic>’"

my model class

import 'package:object_mapper/object_mapper.dart';

class BottomNavListItem with Mappable {
int? id;
String? name;

@override
void mapping(Mapper map) {
map("id", id, (v) => id = v);
map("name", name, (v) => name = v);
}

}

response handling class

Future<List<BottomNavListItem>?> getFamilyStatus(String url) async {
Response response;
List<BottomNavListItem>? bottomNavListModel;
try {
response = await WebUtil.createDio().get(url);
if (kDebugMode) {
print(response.data.toString());
}
bottomNavListModel =
Mapper.fromJson(response.data).toObject<List<BottomNavListItem>>();
} on DioError catch (e) {

print(response.data.toString()); will prints :
[{id: 1, name: test}, {id: 2, name: MiddleClass}, {id: 3, name: UpperMiddleClass}, {id: 4, name: Rich}]
which is Json Array in correct format.
Anybody knows a solution pls help….

3

Answers


  1. The result that you got from the Dio is a List of Maps (not a Map), which may be a List<Map<String, dynamic>>.

    You need to convert each of its items to BottomNavListItem with something like this:

    List<BottomNavListItem>? bottomNavListModel;
    
    bottomNavListModel = response.data
        .map((e) => Mapper.fromJson(e).toObject<BottomNavListItem>()!)
        .toList();
    
    Login or Signup to reply.
  2. The response that you are getting is list of a Map

    So you can’t do Mapper.fromJson(response.data) directly on response .

    You can instead iterate through each item and call Mapper.fromJson(response[i].data) may this will help.

    or to debug more easily you can try to find out runTimeType of your response
    by using print(response.runTimeType)

    Login or Signup to reply.
  3. you need to parse the data like this

     response.data.forEach((item){
          bottomNavListModel?.add(BottomNavListItem.fromJson(item));
        });
    

    and update model like this…

    class BottomNavListItem with Mappable {
      int? id;
      String? name;
    
      @override
      void mapping(Mapper map) {
        map("id", id, (v) => id = v);
        map("name", name, (v) => name = v);
      }
    
      BottomNavListItem.fromJson(Map<String, dynamic> json) {
        id = json['id'];
        name = json['name'];
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search