Home > database >  Flutter - Unhandeled Exception: Null is not subtype of Map<String, dynamic>
Flutter - Unhandeled Exception: Null is not subtype of Map<String, dynamic>

Time:11-29

I'm working on a YouTube project. Here I have an API of type json I'm doing data conversion between dart and json objects. Json API code :

{
"kind": "youtube#searchListResponse",
"etag": "5onvX79jNWnZR6_9hCnQcHqW7X8",
"nextPageToken": "CAgQAA",
"regionCode": "PK",
"pageInfo": {
  "totalResults": 1000000,
  "resultsPerPage": 8
 },
}

Sub-json object code conversion :

class PageInfoData {
final int totalResults;
final int resultPerPage;

PageInfoData({required this.totalResults, required this.resultPerPage});

factory PageInfoData.fromJson(Map<String,dynamic>json,){
    return PageInfoData(
      totalResults: json['totalResults'],
      resultPerPage: json['resultPerPage'],
     );
   }

 }

The YouTube Page convert json to dart code :

class YouTubeSearchModel {
final String kind;
final String etag;
final String nextPageToken;
final String regionCode;
final PageInfoData pageinfo;

YouTubeSearchModel({
  required this.kind,
  required this.etag,
  required this.nextPageToken,
  required this.regionCode,
  required this.pageinfo,
});

factory YouTubeSearchModel.fromJson(Map<String,dynamic>json){
  return YouTubeSearchModel(
    etag: json['kind'],
    kind: json['etag'],
    nextPageToken: json['nextPageToken'],
    regionCode : json['regionCode'],
    pageinfo: PageInfoData.fromJson(json['pageinfo'])

   );
 }

}

Exception is in the PageInfo(sub-json-object). Am I doing something wrong here? If you have any clue/fix for this Exception please share I'd be thankful <3

CodePudding user response:

You have some typos in your model classes.

In PageInfoData json['resultPerPage'] should be json['resultsPerPage']:

class PageInfoData {
  final int totalResults;
  final int resultPerPage;

  PageInfoData({required this.totalResults, required this.resultPerPage});

  factory PageInfoData.fromJson(Map<String, dynamic> json) {
    return PageInfoData(
      totalResults: json['totalResults'],
      resultPerPage: json['resultsPerPage'],
    );
  }
}

In YouTubeSearchModel json['pageinfo'] should be json['pageInfo']:

class YouTubeSearchModel {
  final String kind;
  final String etag;
  final String nextPageToken;
  final String regionCode;
  final PageInfoData pageinfo;

  YouTubeSearchModel({
    required this.kind,
    required this.etag,
    required this.nextPageToken,
    required this.regionCode,
    required this.pageinfo,
  });

  factory YouTubeSearchModel.fromJson(Map<String, dynamic> json) {
    return YouTubeSearchModel(
        etag: json['kind'],
        kind: json['etag'],
        nextPageToken: json['nextPageToken'],
        regionCode: json['regionCode'],
        pageinfo: PageInfoData.fromJson(json['pageInfo']));
  }
}
  • Related