arrays - 在 dart 中解析对象(不支持的操作:无法添加到固定长度列表)
问题描述
当用户登录/注册时,我有一个用户对象保存到云 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());
}}
当用户注销然后他登录并尝试对用户对象进行操作时,这里出现了一些属性(列表类型)无法使用的问题。此代码创建项目并添加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;
}
}
解决方案
这对我有用:
list = list.toList();
list.add(值);
推荐阅读
- elasticsearch - 无法通过filebeat将日志发送到Kubernetes中的logstash
- permissions - 从数据洞察访问数据时,数据集级别的 BigQuery 数据查看者权限与项目级别的权限有何区别?
- java - SpringBoot骆驼单元测试导致camelContext错误
- go - 转换为 DataResponse 的参数过多
- sql - 如何在 SQL 中对一组自定义计算字段求和?
- intellij-idea - 如何打开在 Intellij 中导出的图表?
- mongodb - 是否有任何标准工具可以在启动期间使用 Spring Boot 更新 MongoDB 集合?
- javascript - ReactJs:由于不推荐使用componentWillMount,如何在组件安装之前执行代码?
- excel - 如何让我的代码在任何工作表上运行
- apache-kafka - Apache Camel Kafka:如何在生产者配置中设置属性“delivery.request.ms”