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:
object['movement']
doesn't exist.object['movement']
it mayn't provide every time non null values.
Solutions:
- check if the name is correct in JSON.
- If it provides null then assign an empty list or any default list with the operator
??
.
Thanks.