dart中解析对象(不支持的操作:无法添加到定长列表)

问题描述 投票:0回答:4

我有一个用户对象,当用户登录/注册时,该对象保存到云Firestore数据库中。 因此,当他登录时,会从数据库中检索用户对象,并且一切正常,直到我尝试在列表“usersProject”上执行“添加”操作:

// Add the new project ID to the user's project list
user.userProjectsIDs.add(projectID);

所以我得到了例外

Unhandled Exception: Unsupported operation: Cannot add to a fixed-length list
我相信问题在于将用户从 json 转换为对象时,因为当用户注册时,对象会转换为 json 并存储在数据库中,并且用户将在转换之前使用该对象自动登录。

void createUser(String email, String password, String username, String name, String birthDate) async {
try {
  // Check first if username is taken
  bool usernameIsTaken = await UserProfileCollection()
      .checkIfUsernameIsTaken(username.toLowerCase().trim());
  if (usernameIsTaken) throw FormatException("Username is taken");

  // Create the user in the Authentication first
  final firebaseUser = await _auth.createUserWithEmailAndPassword(
      email: email.trim(), password: password.trim());

  // Encrypting the password
  String hashedPassword = Password.hash(password.trim(), new PBKDF2());

  // Create new list of project for the user
  List<String> userProjects = new List<String>();

  // Create new list of friends for the user
  List<String> friends = new List<String>();

  // Creating user object and assigning the parameters
  User _user = new User(
    userID: firebaseUser.uid,
    userName: username.toLowerCase().trim(),
    email: email.trim(),
    password: hashedPassword,
    name: name,
    birthDate: birthDate.trim(),
    userAvatar: '',
    userProjectsIDs: userProjects,
    friendsIDs: friends,
  );

  // Create a new user in the fire store database
  await UserProfileCollection().createNewUser(_user);
  
  // Assigning the user controller to the 'user' object
    Get.find<UserController>().user = _user;
    Get.back();

} catch (e) {
  print(e.toString());
}}

当用户注销后,再登录并尝试对用户对象进行操作时,就会出现一些属性(List类型)无法使用的问题。 此代码创建项目并将

projectID
添加到用户列表

  Future<void> createNewProject(String projectName, User user) async {

String projectID = Uuid().v1(); // Project ID, UuiD is package that generates random ID

// Add the creator of the project to the members list and assign him as admin
var member = Member(
  memberUID: user.userID,
  isAdmin: true,
);
List<Member> membersList = new List();
membersList.add(member);

// Save his ID in the membersUIDs list
List <String> membersIDs = new List();
membersIDs.add(user.userID);

// Create chat for the new project
var chat = Chat(chatID: projectID);

// Create the project object
var newProject = Project(
  projectID: projectID,
  projectName: projectName,
  image: '',
  joiningLink: '$projectID',
  isJoiningLinkEnabled: true,
  pinnedMessage: '',
  chat: chat,
  members: membersList,
  membersIDs: membersIDs,
);


// Add the new project ID to the user's project list
user.userProjectsIDs.add(projectID);

try {
  // Convert the project object to be a JSON
  var jsonUser = user.toJson();

  // Send the user JSON data to the fire base
  await Firestore.instance
      .collection('userProfile')
      .document(user.userID)
      .setData(jsonUser);

  // Convert the project object to be a JSON
  var jsonProject = newProject.toJson();

  // Send the project JSON data to the fire base
  return await Firestore.instance
      .collection('projects')
      .document(projectID)
      .setData(jsonProject);
} catch (e) {
  print(e);
}}

这里发生异常的地方只有当用户注销然后登录时,但是当他第一次注册时不会出现异常。

 // Add the new project ID to the user's project list
user.userProjectsIDs.add(projectID);

签到功能

void signIn(String email, String password) async {
try {
  // Signing in
  FirebaseUser firebaseUser = await _auth.signInWithEmailAndPassword(email: email.trim(), password: password.trim());

  // Getting user document form firebase
  DocumentSnapshot userDoc = await UserProfileCollection().getUser(firebaseUser.uid);
 

  // Converting the json data to user object and assign the user object to the controller
  Get.find<UserController>().user = User.fromJson(userDoc.data);
  print(Get.find<UserController>().user.userName);

} catch (e) {
  print(e.toString());
}}

我认为问题是由

User.fromJson
引起的 为什么它使 firestore 中的数组不可修改?

用户类别

class User {
  String userID;
  String userName;
  String email;
  String password;
  String name;
  String birthDate;
  String userAvatar;
  List<String> userProjectsIDs;
  List<String> friendsIDs;

  User(
      {this.userID,
      this.userName,
      this.email,
      this.password,
      this.name,
      this.birthDate,
      this.userAvatar,
      this.userProjectsIDs,
      this.friendsIDs});

  User.fromJson(Map<String, dynamic> json) {
    userID = json['userID'];
    userName = json['userName'];
    email = json['email'];
    password = json['password'];
    name = json['name'];
    birthDate = json['birthDate'];
    userAvatar = json['UserAvatar'];
    userProjectsIDs = json['userProjectsIDs'].cast<String>();
    friendsIDs = json['friendsIDs'].cast<String>();
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['userID'] = this.userID;
    data['userName'] = this.userName;
    data['email'] = this.email;
    data['password'] = this.password;
    data['name'] = this.name;
    data['birthDate'] = this.birthDate;
    data['UserAvatar'] = this.userAvatar;
    data['userProjectsIDs'] = this.userProjectsIDs;
    data['friendsIDs'] = this.friendsIDs;
    return data;
  }
}

arrays json flutter dart google-cloud-firestore
4个回答
31
投票

只需添加可增长参数..

如果 [growable] 为 false(默认值),则列表是长度为零的固定长度列表。如果 [growable] 为 true,则列表是可增长的并且相当于 []。

final growableList = List.empty(growable: true);

8
投票

这对我有用:

列表 = list.toList();

列表.add(值);


4
投票

您的 JSON 解码可能会返回固定长度的列表,然后您将使用该列表来初始化

userProjectsIDs
类中的
User
。这会阻止您添加其他元素。

fromJson
构造函数更改以下内容:

userProjectsIDs = json['userProjectsIDs'].cast<String>();

userProjectsIDs = List.of(json['userProjectsIDs'].cast<String>());

0
投票

问题是cast()方法返回一个固定长度的列表。要解决这个问题,只需在像这样cast().toList();这样的转换时添加toList()即可

© www.soinside.com 2019 - 2024. All rights reserved.