flutterdartresponsemapperdio

Flutter parsing error after correct response


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....


Solution

  • 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'];
      }
    }