Unhandled Exception: NoSuchMethodError: The method '[]' was called on null. while parsing json

Unhandled Exception: NoSuchMethodError: The method '[]' was called on null. while parsing json

我有一个 json 对象,其中包含一个可能为空的对象。 这是我的 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 字段有数据,第二个元素为空。 这是我的视图模型:

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'],
      );
}

解析时出现异常:

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")

这是我的存储库:

final items = (data['elements'] as List)
        .map((final e) => UnitItemViewModel.fromJson(
              e as Map<String, dynamic>,
            ))
        .toList();

任何想法都会很棒。

这一行你得到错误,因为 jsonnull

firstName: json['firstName']

您应该像这样更改此 fromJson 函数:

factory UnitOwner.fromJson(final Map<String, dynamic>? json) => UnitOwner(
        firstName: json?['firstName'] ?? '',
        lastName: json?['lastName'] ?? '',
        mobile: json?['mobile'] ?? '',
      );