Flutter - 类型 'List<dynamic>' 不是类型 'List<Model>?' 的子类型

Flutter - type 'List<dynamic>' is not a subtype of type 'List<Model>?'

我正在按照一些 youtube 教程制作一个应用程序来学习 flutter。我正在尝试制作搜索结果的列表视图。我能够从节点后端查询和获取数据,但是在将 json 映射到模型时出现此错误。

我从api得到的数据是这样的:

{id: <uuid>, 
userEmail: <email_string>, 
profile: [{profileName: <profile_name_string>, 
    profileImage: <image_url_string>, 
    profileBio: <profile_bio_string>}]
}

使用新模型 class 我按照此处的回答进行了操作,我可以单独获取配置文件模型,但是当我尝试获取包含所有配置文件的帐户模型时,我收到错误消息:type 'List<dynamic>' is not a subtype of type 'List<ProfileModel>?'.模型 class 是:

class AccountModel {
  String userId;
  String userEmail;
  String? userPassword;
  final List<ProfileModel>? profile;

  AccountModel({
    required this.userId,
    required this.userEmail,
    this.userPassword,
    this.profile,
  });
  factory AccountModel.fromJson({required Map<String, dynamic> map}) {
    return AccountModel(
      userId: map['id'],
      userEmail: map['userEmail'],
      userPassword: map['userPassword'],
      profile: map['profile']
          .map((profileJson) => ProfileModel.fromJson(profileJson))
          .toList(),
    );
  }
}

class ProfileModel {
  String profileName;
  String profileImage;
  String? profileBio;

  ProfileModel({
    required this.profileName,
    required this.profileImage,
    this.profileBio,
  });

  factory ProfileModel.fromJson(profileJson, {Map<String, dynamic>? map}) {
    if (map != null) {
      return ProfileModel(
        profileName: map['profileName'],
        profileImage: map['profileImage'] ?? "default",
        profileBio: map['profileBio'],
      );
    } else {
      return ProfileModel(
        profileName: profileJson['profileName'],
        profileImage: profileJson['profileImage'] ?? "default",
        profileBio: profileJson['profileBio'],
      );
    }
  }
}

如何使列表发挥作用?

当您在此处将列表声明为

final List<ProfileModel>? profile;

它期望列表只有 ProfileModels 作为 ListItem,即使带有“?”。解决它的方法是声明一个没有通用 ProfileModel 的列表:

  1. final List? profile;

或者将您正在推送的项目强制转换为 ProfileModel。 2. profile: map['profile'] .map((profileJson) => ProfileModel.fromJson(profileJson) as ProfileModel) .toList(),

我不知道输出结构等,所以如果上面的代码不起作用,请尝试进行类型转换。可能在 toList() 方法之后进行类型转换,因为 List 也可以工作。

在这种情况下,您可以使用 List.from()

profile: map['profile'] != null
      ? List<ProfileModel>.from(
          map['profile']?.map((p) => ProfileModel.fromJson(p)))
      : null)

我们在 ProfileModel 上使用 fromMap,您可以简化分离,而在 ProfileModel 上两者相同。

更多关于 List and List.from