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

2024-06-20

我有一个用户对象,当用户登录/注册时,该对象保存到云 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;
  }
}


只需添加可增长的参数..

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

final growableList = List.empty(growable: true);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐

  • C# 获取子窗口句柄

    我正在用 C 启动一个进程 然后使用 SendMessage 将 Windows 消息发送到该进程 通常我将消息发送到 Process MainWindowHandle 但在某些情况下 我可能需要找到子窗口句柄并向那里发送消息 我将如何在
  • 如何在 MVC3 Razor 视图中呈现数据表

    我在 xls 电子表格 1 之间有一个可靠且经过测试的导入方法 该方法返回DataTable 我已将其定位在我的服务层中 而不是数据中 因为只有工作簿作为上传文件保存 但现在我想知道在哪里以及如何生成此内容的 HTML 表示形式DataTa
  • NSUInteger 的奇怪行为 - 无法正确转换为浮动

    这是我的情况 这让我发疯 我有一个计数值为 517 的 NSMutableArray 我有一个双精度值 它是我的乘数 double multiplier 0 1223 double result myArray count multipli
  • Xamarin Android Webview Javascript

    我正在尝试通过 Xamarin for Android 创建一个移动应用程序 它有一个显示网站的 WebView 问题是正常按钮会触发 但 javascript 事件不会触发 我已经启用了 Javascript 但没有运气 如何在 Andr
  • 如何在C Sharp中使用unity3d从url下载文件并保存在位置?

    我正在从事 unity3d 项目 我需要从服务器下载一组文件 我使用 C 编写脚本 经过一个小时的谷歌搜索后 由于文档不完善 我还没有找到解决方案 谁能给我从 url 下载文件并将其保存在 unity3d 中的特定位置的示例代码 Unity
  • OpenCV OpenNI 校准kinect

    我使用 home 通过 kinect 进行捕捉 capture retrieve depthMap CV CAP OPENNI DEPTH MAP capture retrieve bgrImage CV CAP OPENNI BGR IM
  • Flutter:带有嵌套导航的底部导航栏,并在选项卡更改时恢复根页面

    我是 Flutter 开发的新手 我已经阅读了多个教程来了解底部导航栏 我已经尝试过这些教程 但无法达到我的要求 我遵循的教程 https codewithandrea com articles multiple navigators bo
  • 无法在 Swift 中对闭包进行弱引用

    Update 我试着不弱化地写一下 好像也没有漏的情况 所以也许这个问题已经没有必要了 在 Objective C ARC 中 当你想让一个闭包能够在闭包内部使用它自己时 该块不能捕获对自身的强引用 否则它将是一个保留循环 因此您可以使闭包
  • IE7 显示问题:菜单中的表格

    我写了一个菜单样式 在 IE8 FF3 6 GC7 中运行良好 现在的问题是 我的老板希望它甚至可以在 IE7 上运行 我真的很努力地让它在 IE7 上运行 但无法获得相同的外观 menu css a outline none menu m
  • 选中/取消选中所有复选框

    我见过很多选中 取消选中所有复选框的脚本 但大多数人并不尊重这一点 如果我使用 全部选中 复选框切换所有复选框 然后取消选中列表中的单个复选框 则 全部选中 复选框仍处于选中状态 有没有一种优雅的方式来处理这种情况 checkAll cli
  • 解析带下划线的 SQL Server 数字文字

    我想知道它为什么有效以及为什么它不返回错误 SELECT 2015 11 Result 11 2015 第二种情况 SELECT 2 1 a a 2 1 检查元数据 SELECT name system type name FROM sys
  • 如何在 JMeter 中显示实际循环计数

    我们可以通过以下方式显示实际线程 threadNum 实际循环计数有类似的东西吗 您可以使用 jm Thread Group idx 获取当前循环迭代 jm Thread Group idx 请注意 这是 JMeter 5 中一般增强功能的
  • 从响应中获取标头(Retrofit / OkHttp 客户端)

    我正在使用 Retrofit 与 OkHttp 客户端和 Jackson 进行 Json 序列化 并希望获取响应的标头 我知道我可以扩展 OkClient 并拦截它 但这发生在反序列化过程开始之前 我基本上需要的是获取标头以及反序列化的 J
  • Android Studio:XML 布局中的“包装在容器中”

    编辑 XML 布局文件时 Eclipse 有一项称为 包裹在容器中 的功能 重新格式化 gt Android gt 可让您选择一个或多个视图并在其周围包裹您选择的布局 Android Studio中有类似的东西吗 目前正在实施中 问题 69
  • 无法将 .ogg 文件转换为 .mp3 或其他文件格式

    我正在尝试将 ogg 音频文件转换为 mp3 或其他可以在 ios 设备中播放的音频文件格式 但 ogg 文件没有被转换为其他格式 如 mp3 和 caf 我正在 Android 设备中测试转换 这是我的 ffmpeg 命令参数 Comma
  • CDATA 真的有必要吗?

    我经常使用内联 Javascript 通常是在我制作的 WordPress 主题中 我没有听说过将内联 Javascript 包装在 直到几个月前 几年来我一直在以相当的能力水平做这些事情 我用谷歌搜索了一下 听说人们使用它是因为他们的 J
  • 从 Firefox 33.0.2 中的 javascript 清除 ssl 客户端证书状态(已删除专有 window.crypto)

    我正在寻找一种方法来清除 Firefox 中的 SSL 客户端证书缓存 作为一种 注销 功能 以便服务器在我下次连接到服务器时不再通过客户端证书识别我 解决方案来自从 JavaScript 清除 ssl 客户端证书状态 https stac
  • C#:编译表达式时已添加具有相同键的项目

    好吧 这是一个棘手的问题 希望这里有一位表达大师能够发现我在这里做错了什么 因为我只是不明白 我正在构建用于过滤查询的表达式 为了简化这个过程 我有几个Expression
  • 生成具有固定数字长度的随机数?

    我正在生成随机数 int randomID arc4random 3000 但我想生成至少 4 位数字的随机数 如 1000 2400 1122 我想知道 Objective C 的代码 请尝试 生成数字 1000 9999 int ran
  • dart中解析对象(不支持的操作:无法添加到固定长度列表)

    我有一个用户对象 当用户登录 注册时 该对象保存到云 Firestore 数据库中 因此 当用户登录时 将从数据库中检索用户对象 并且一切正常 直到我尝试对列表 usersProject 执行 添加 操作 Add the new proje