Kevin Yang
Kevin Yang

Reputation: 737

flutter) type 'List<dynamic>' is not a subtype of type 'List<String>'

I want to get user model after registration is completed with firebase email auth. However, when I attempt to get a user model from firestore, the following error is printed:

type 'List<dynamic>' is not a subtype of type 'List<String>'

My user model is as follows

class UserModel {
  late String userKey;
  late String nickname;
  late String email;
  late List<String> listItem; // error!!
  late GeoFirePoint geoFirePoint; 
  late bool isPostOn; 
  late bool isLogin;
  late DateTime createdDate;

  DocumentReference? reference; 

  UserModel({
   ....
  });

  UserModel.fromJson(Map<String, dynamic> json, this.userKey) // this.reference
      : nickname = json[DOC_NICKNAME],
        ....
        createdDate = json[DOC_CREATEDDATE] == null
            ? DateTime.now().toUtc()
            : (json[DOC_CREATEDDATE] as Timestamp).toDate();

  UserModel.fromSnapshot(DocumentSnapshot<Map<String, dynamic>> snapshot)
      : this.fromJson(snapshot.data()!, snapshot.id);

  Map<String, dynamic> toJson() {
    var map = <String, dynamic>{};
    map[DOC_NICKNAME] = nickname;
    ....
    return map;
  }
}

And this is getting a user model from Firestore. // class UserService

  Future<UserModel> getUserModel(String userKey) async {
    DocumentReference<Map<String, dynamic>> documentReference =
        FirebaseFirestore.instance.collection(COL_USERS).doc(userKey);

    final DocumentSnapshot<Map<String, dynamic>> documentSnapshot =
        await documentReference.get();

    UserModel userModel = UserModel.fromSnapshot(documentSnapshot);
    return userModel;
  }

// user provider

  Future _setNewUser(User? user) async {
    if (user != null && user.email != null) {
      ....
      // ! Error
      // test 1
      // List<String> subjectList = prefs.getStringList(SHARED_SUBJECTS) ?? [];

      // test 2
      List<String> listItem =
          prefs.getStringList(SHARED_ITEM)?.cast<String>() ??
              [].cast<String>();
   
      String email = user.email!;
      String userKey = user.uid;

      UserModel userModel = UserModel(
        userKey: "",
        listItem: listItem, // error
        ....
      );

      // create model and firestore upload
      await UserService().createNewUser(userModel.toJson(), userKey);

      // get user model, error!!
      try {
        _userModel = await UserService().getUserModel(userKey);
      } catch (e) {
        logger.w("get model error: $e");
      }
     }
    }

What should I do with List data to resolve this issue? Thank you!

Upvotes: 7

Views: 4227

Answers (1)

Julian
Julian

Reputation: 473

You have to convert the list:

listItem = List<String>.from(data['listItem'])

Upvotes: 12

Related Questions