【问题标题】:type 'List<dynamic>' is not a subtype of type 'List<String>' flutter类型“List<dynamic>”不是“List<String>”类型的子类型
【发布时间】:2021-07-06 16:58:45
【问题描述】:

我正在从 firebase 获取数据并使用 fromJson 构造函数对其进行覆盖,但它会引发错误。导致的问题是模型中的类别列表,我已经完成了铸造方法,但它仍然无法正常工作。请帮助我,我从 2 天开始就被困在这里。任何解决方案都不适合我

这是个例外

======== Exception caught by widgets library =======================================================
The following _TypeError was thrown building FutureBuilder<DocumentSnapshot>(dirty, state: _FutureBuilderState<DocumentSnapshot>#6cd83):
type 'List<dynamic>' is not a subtype of type 'List<String>'

The relevant error-causing widget was: 
  FutureBuilder<DocumentSnapshot> file:///E:/flutterProject/filmmaker/lib/auth_screens/signUp_screens/worker/signUp_screen14.dart:93:30
When the exception was thrown, this was the stack: 
#0      new UserInfoModel.fromMap (package:filmmaker/resources/models/user_info.dart:88:19)
#1      _SignUpScreen14State._nameCountry.<anonymous closure> (file:///E:/flutterProject/filmmaker/lib/auth_screens/signUp_screens/worker/signUp_screen14.dart:102:46)
#2      _FutureBuilderState.build (package:flutter/src/widgets/async.dart:773:55)
#3      StatefulElement.build (package:flutter/src/widgets/framework.dart:4612:27)
#4      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4495:15)
...
====================================================================================================

这是我未来的构建器小部件,我正在从 firestore 获取数据并将其发送到 fromJson 构造函数

Widget get _nameCountry => FutureBuilder<DocumentSnapshot>(
        future: FirebaseRepo.instance.fetchWorkerDataFromDb(),
        builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
          switch (snapshot.connectionState) {
            case ConnectionState.waiting:
              return CircleAvatar(
                radius: 80.0,
              );
            case ConnectionState.done:
              _userInfoModel = UserInfoModel.fromMap(snapshot?.data?.data());
        //      Map<String, dynamic> data = snapshot?.data?.data();
              return Row(
                children: <Widget>[
                  Text('${_userInfoModel.name}, '),
                  Text('${_userInfoModel.country}, '),                ],
              );
            default:
              return Text(
                snapshot.error,
                textAlign: TextAlign.center,
              );
          }
        },
        // child: Row(
        //       children: <Widget>[Text('${_userInfoModel.name} ,'), Text('')],
        //     ),
      );

我的模型函数

class UserInfoModel {
  String uid,
      name,
      email,
      userName,
      status,
      profilePhoto,
      country,
      profileState,
      expert,
      englishProficiency,
      title,
      professionalOverview,
      phoneNo,
      hourlyRate,createdAt;
  bool signUpCheckForEmail;
  List<String> categories, skills, otherLanguages;
  List<Map> education, employment;
  Map companyData,companyContacts;


  UserInfoModel(
      {this.uid,
      this.name,
      this.email,
      this.userName,
      this.status,
      this.profilePhoto,
      this.country,
      this.profileState,
      this.signUpCheckForEmail,
      this.categories,
      this.skills,
      this.expert,
      this.education,
      this.employment,
      this.englishProficiency,
      this.otherLanguages,
      this.title,
      this.professionalOverview,
      this.companyData,
      this.phoneNo,
      this.hourlyRate,
      this.companyContacts,
      this.createdAt});

  Map toMap(UserInfoModel user) {
    var data = Map<String, dynamic>();
    data['uid'] = user.uid;
    data['name'] = user.name;
    data['email'] = user.email;
    data['userName'] = user.userName;
    data['status'] = user.status;
    data['profilePhoto'] = user.profilePhoto;
    data['country'] = user.country;
    data['profileState'] = user.profileState;
    data['signUpCheckForEmails'] = user.signUpCheckForEmail;
    data['categories'] = user.categories;
    data['skills'] = user.skills;
    data['expert'] = user.expert;
    data['education'] = user.education;
    data['employment'] = user.employment;
    data['english proficiency'] = user.englishProficiency;
    data['other languages'] = user.otherLanguages;
    data['professionalOverview'] = user.professionalOverview;
    data['title'] = user.title;
    data['companyData'] = user.companyData;
    data['phoneNo'] = user.phoneNo;
    data['hourlyRate'] = user.hourlyRate;
    data['companyContacts'] = user.companyContacts;
    data['createdAt']= user.createdAt;
    return data;
  }

  factory UserInfoModel.fromMap(Map<String, dynamic> data) {
    return UserInfoModel(
      uid: data['uid'],
      name: data['name'],
      email: data['email'],
      userName: data['userName'],
      status: data['status'],
      profilePhoto: data['profilePhoto'],
      country: data['country'],
      profileState: data['profileState'],
      signUpCheckForEmail: data['signUpCheckForEmails'],
      categories: data['categories'].cast<String>(),
      skills: data['skills'],
      expert: data['expert'],
      education: data['education'],
      employment: data['employment'],
      englishProficiency: data['english proficiency'],
      otherLanguages: data['other languages'],
      professionalOverview: data['professionalOverview'],
      title: data['title'],
      companyData: data['companyData'],
      phoneNo: data['phoneNo'],
      hourlyRate: data['hourlyRate'],
      companyContacts: data['companyContacts'],
      createdAt:  data['createdAt'],
    );
  }
}

【问题讨论】:

    标签: json firebase flutter dart google-cloud-firestore


    【解决方案1】:

    我用一些虚拟数据运行了你的代码,cast&lt;String&gt; for categories 对我有用。但是,您尚未将演员表添加到 skillsotherLanguages。您是否检查了错误的行号?如果问题肯定出在categories,您能否在问题中添加一些示例数据。

    【讨论】:

    • 我已将转换为其他类型,现在错误是“类型 'List' 不是类型 'List>' 的子类型”
    • 这听起来像是一个不同的错误,因为它说源是类型List&lt;Map&lt;dynamic,dynamic&gt;&gt;
    【解决方案2】:

    尝试将List&lt;String&gt; categories, skills, otherLanguages;替换为动态并移除强制转换

    List&lt;dynamic&gt; categories, skills, otherLanguages;

    【讨论】:

    • 最好有强类型模式(并修复映射代码)。
    • 是的,我刚刚测试过,但仍然无法正常工作,所以现在我正在这样做 Text('data['name'] '),
    • 谢谢我刚刚再次测试,它工作正常。我已经合并了这两个答案,并且解决方案是最佳的
    • 我重复我的评论,在模型类中使用dynamic 不是一个好主意,最好有强类型。在我的测试中,当应用于所有需要它的语句时,演员表工作正常。
    猜你喜欢
    • 2021-12-29
    • 2023-01-08
    • 2021-02-17
    • 2021-07-17
    • 2019-11-07
    • 1970-01-01
    • 2021-10-25
    • 2020-07-03
    • 2019-12-05
    相关资源
    最近更新 更多