Search code examples
jsonflutterdartjson-deserialization

Flutter/Dart Error - NoSuchMethodError (NoSuchMethodError: Class 'String' has no instance method 'map'


I receive an error that has something to do with JSON receiver inside Flutter/Dart.

Had to share in a docs file since the full json response is pretty long. It had like 15 columns error log

Detail Class

class Detail {
String kodkursus;
String namakursus;
String kursusdescription;

Detail(
  {required this.kodkursus,
  required this.namakursus,
  required this.kursusdescription});

factory Detail.fromJson(Map<String, dynamic> json) {
return Detail(
  kodkursus: json['crs_code'] as String,
  namakursus: json['crs_title_bm'] as String,
  kursusdescription: json['crs_description_bm'] as String,
  
);
}
}

Code

Future<dynamic> generateDetailList() async {
var url = 'http://10.0.2.2:81/login_testing/kursus_display.php';
var data = {'usr_id': widget.username2};
var response = await http.post(url, body: json.encode(data));

var list = json.decode(json.encode(response.body));

List<Detail> _detail =
    list.map<Detail>((json) => Detail.fromJson(json)).toList();
detailDataSource = DetailDataSource(_detail);
return _detail;
}

Return (full error log)

NoSuchMethodError (NoSuchMethodError: Class 'String' has no instance method 'map'...

I fairly new to this Flutter/Dart but I got the feeling it had something to do with the json, it just I cant get my head over it


Solution

  • Please check your API response because this error generates when there are difference in datatype.

    this error says your app response it in String and you are accessing this as map so please check your API response or

    try to replace this :

    var list = json.decode(json.encode(response.body));
    

    with :

    var list = json.decode(response.body);
    

    because json.encode method encodes all list data and that values datatype is String so it gives error.