Home > OS >  Flutter _CastError (type 'Null' is not a subtype of type 'List<dynamic>' i
Flutter _CastError (type 'Null' is not a subtype of type 'List<dynamic>' i

Time:04-08

How Can I check if null?

  factory PostResult.createPostResult(Map<String, dynamic> object) {
return PostResult(
  caseId: object['case_id'],
  serial: object['serial'],
  movement: (object['movement'] as List)
      .map((e) => Content.fromJson(e as Map<String, dynamic>))
      .toList()
);

}

I receive this error:

Flutter _CastError (type 'Null' is not a subtype of type 'List' in type cast)

CodePudding user response:

It seems that object['movement'] is null.

movement: object['movement'] == null ? null : List<Content>.from(object["movement"].map((e) => Content.fromJson(e))) 

CodePudding user response:

You can use ?? operator to set default value if null.

In this case, object['movement'] can be null(not exits will return null) and when it null, a empty list [] was used instead.

movement: (object['movement'] ?? [])
      .map((e) => Content.fromJson(e as Map<String, dynamic>))
      .toList()

// When object['movement'] = null, movement = []

CodePudding user response:

Possibilities:

  1. object['movement'] doesn't exist.
  2. object['movement'] it mayn't provide every time non null values.

Solutions:

  1. check if the name is correct in JSON.
  2. If it provides null then assign an empty list or any default list with the operator ?? .

Thanks.

  • Related