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

费萨尔

我有一个用户对象,该用户对象在用户登录/注册时保存到了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解码可能会返回固定长度的列表,然后将其用于userProjectsIDsUser类中进行初始化这样可以防止您添加其他元素。

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

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

flutter:不支持的操作:无法添加到无法修改的列表

无法添加到github:Gist不支持目录

使用sum函数在列表中添加对象时不支持的操作数类型错误

不支持的操作:无法解析引用

TypeError:对象在IE 11中不支持此操作

是什么使它成为Dart中的定长列表?

无法将文件添加到tar:存档/ tar:不支持套接字

无法将对象添加到我的列表中

无法添加对象并将列表一起添加到对象列表中

将列表列表中的平面列表添加到固定长度的numpy数组中

如何使用React MaterialUI将分页添加到长列表中?

无法添加到ArrayList中的对象

无法添加到ArrayList中的对象

在 python 中显示列表中的素数。错误说不支持的操作数

错误:不支持输入“ int []”字段 如何将整数列表添加到Realm?

在Laravel中通过单击按钮将用户ID添加到帖子中,会显示错误消息“不支持帖子方法”

激活并将值添加到单元格时,Excel VBA-“对象不支持此属性或方法”

不支持的操作:Android,Retrofit,OkHttp。在OkHttpClient中添加拦截器

Python:在python中添加2个函数输出时不支持的操作数?

Angular2:对象在 Microsoft Edge 浏览器中不支持此操作

iPhone不支持任何应用程序体系结构。您可以将arm64e架构添加到应用的“架构”构建设置中

將一列假數據添加到 pyspark 中的數據幀:不支持的文字類型類

如何将地图添加到 Dart 中的列表

对象不支持此操作

Laravel 5.4中不支持的操作数类型

Laravel 6 中不支持的操作数类型

对象未添加到列表中,列表返回空

无法将对象添加到EventInput数组,FullCalendar,Angular的列表中

无法将派生类对象添加到其基类类型的列表中