Home > Enterprise >  Cast to model List<Map<String,dynamic>> issue flutter
Cast to model List<Map<String,dynamic>> issue flutter

Time:10-15

I want convert my response API to model repository in flutter but always get error in type of model use Dio for api request this is my response API :

{
    "success": 1,
    "list": [
        {
            "id": "1",
            "driver_id": "11081",
            "company_id": "9",
            "school_id": "4",
            "status": 1,
            "createdAt": "2022-10-14T09:22:00.000Z",
            "updatedAt": "2022-10-14T09:22:03.000Z"
        },
        {
            "id": "2",
            "driver_id": "11081",
            "company_id": "9",
            "school_id": "5",
            "status": 1,
            "createdAt": "2022-10-14T20:36:47.000Z",
            "updatedAt": "2022-10-14T20:36:49.000Z"
        }
    ]
}

I try get data like this :

Future<List<ServiceEntity>> getAll() async {
    final List<ServiceEntity> services = [];
    try {
      final response = await httpClient.post("v1/teacher/get-list");
      validateResponse(response);

      (response.data['list'] as List).forEach((jsonObject) {
        
        services.add(ServiceEntity.fromJson(jsonObject));
      });
    } on DioError catch (e) {
      exceptionHttpRequest(e);
    }

    return services;
  }

and model is :

class ServiceEntity {
  final int id;


  ServiceEntity.fromJson(Map<String, dynamic> json)
      : id = json['id'];
}

When i build app and debug always get this error : I/flutter (29931):

type 'String' is not a subtype of type 'int'

I test many things but in fact did not understand what is the issue

CodePudding user response:

Your id data type is String on response, to use it as int on model class you can parse to int,

id = int.tryParse(json['id']) ?? 0;

if parser failed, it will get 0.

More about converting json and tryParse

CodePudding user response:

The problem is exactly what the error says. String is not a subtype of int.

Look at the data:

  • The "id" is stored as a String.
  • Then you try pull it out in the ServiceEntitys fromJson to an int.

a. Either just store the value as an int, because that's what it is, just b like the success field. b. or parse the string into an int.

Below an example with chatty printing to explain the type changes.

   const data = {
     "id": "1",
   };
   
   try{
     // value stored as a String
     final value = data["id"] as String;
     print(value.runtimeType);
     print(value);
 
     // parse into an int
     final id = int.tryParse(value);
     print(id.runtimeType);
     print(id);
   }catch(e){
     print("ERROR ${e}");
   }
  • Related