i have a json object that includes an object that could be null. here is my json:
I/flutter (23570): ║ {
I/flutter (23570): ║ elements: [
I/flutter (23570): ║ {
I/flutter (23570): ║ id: 1,
I/flutter (23570): ║ name: "a1",
I/flutter (23570): ║ owner: {firstName: امین, lastName: جمالی, mobile: 9014523821}
I/flutter (23570): ║ },
I/flutter (23570): ║ {id: 2, name: a2}
I/flutter (23570): ║ ],
I/flutter (23570): ║ totalElements: 2
I/flutter (23570): ║ }
owner filed in first element has data and in second one is empty. here is my view model:
class UnitItemViewModel {
final int id;
final String name;
UnitOwner? owner;
UnitItemViewModel({
required this.id,
required this.name,
this.owner,
});
factory UnitItemViewModel.fromJson(final Map<String, dynamic> json) =>
UnitItemViewModel(
id: json['id'],
name: json['name'],
owner: UnitOwner.fromJson(json['owner']),
);
}
class UnitOwner {
final String firstName, lastName;
final String mobile;
UnitOwner({
required this.firstName,
required this.lastName,
required this.mobile,
});
factory UnitOwner.fromJson(final Map<String, dynamic> json) => UnitOwner(
firstName: json['firstName'],
lastName: json['lastName'],
mobile: json['mobile'],
);
}
while parsing i got this exception:
E/flutter (23570): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception:
NoSuchMethodError: The method '[]' was called on null.
E/flutter (23570): Receiver: null
E/flutter (23570): Tried calling: []("firstName")
and here is my repository:
final items = (data['elements'] as List)
.map((final e) => UnitItemViewModel.fromJson(
e as Map<String, dynamic>,
))
.toList();
any idea will be great.
CodePudding user response:
This line you get error because json
is null
firstName: json['firstName']
You should change this fromJson function like this :
factory UnitOwner.fromJson(final Map<String, dynamic>? json) => UnitOwner(
firstName: json?['firstName'] ?? '',
lastName: json?['lastName'] ?? '',
mobile: json?['mobile'] ?? '',
);