gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 03:20:09 25 4
gpt4 key购买 nike

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

// 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());
}}
当用户注销后,他登录并尝试对用户对象进行操作,这带来了一些属性(列表类型)无法使用的问题。
此代码创建项目并将 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;
}
}

最佳答案

JSON解码可能返回固定长度的列表,然后将其用于初始化userProjectsIDs类中的User。这样可以防止您添加其他元素。
fromJson构造函数更改以下内容:

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

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

关于arrays - 在dart中解析对象(不支持的操作:无法添加到定长列表),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63909144/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com