Flutter中Amplify生成的UserModel列表添加元素报错求助
解决Amplify生成UserModel列表无法修改的问题
问题原因
Amplify从数据源返回的模型实例中,列表字段默认是固定长度的不可变列表(比如通过List.unmodifiable生成),哪怕你在模型初始化时写了followers: []和following: [],实际获取到的实例列表并不支持增删操作,直接调用add/remove就会触发Unsupported operation: Cannot add to a fixed-length list错误。
解决方案
在修改列表前,先将原不可变列表转换为可扩容的列表,再进行操作,最后通过copyWith生成新的User实例提交修改。
修改后的代码
void followOneUser( User currentUser, User user, BuildContext context, ) async { // 把原不可变列表转为可扩容列表 final currentFollowing = List<String>.from(currentUser.following); final userFollowers = List<String>.from(user.followers); if (currentFollowing.contains(user.id)) { currentFollowing.remove(user.id); userFollowers.remove(currentUser.id); } else { currentFollowing.add(user.id); userFollowers.add(currentUser.id); } // 用新列表生成更新后的User实例 final updatedCurrentUser = currentUser.copyWith(following: currentFollowing); final updatedUser = user.copyWith(followers: userFollowers); final result = await ref.watch(userRepoProvider.notifier).followUser( updatedCurrentUser, updatedUser, ); result.fold( (l) => context.showError(l), (r) async { final res = await ref.watch(userRepoProvider.notifier).incrementFollowing( updatedCurrentUser, updatedUser, ); res.fold( (l) => context.showError(l), (r) => null, ); }, ); }
补充说明
- Amplify生成的模型类遵循不可变设计,直接修改实例字段不符合其设计规范,也会触发错误
- 使用
List.from()或toList()是将不可变列表转为可扩容列表的通用方法 - 始终通过
copyWith创建新实例,确保数据修改的不可变性和正确性
内容的提问来源于stack exchange,提问作者khomotjo_codes
相关产品推荐
相关产品推荐

