不支持的操作:无法添加到固定长度列表

问题描述 投票:0回答:1

您好,我有一个 Flutter 应用程序和一个由

UserModel
生成的
Amplify
。在
UserModel
中,我有两个名为
followers
following
的字段,它们是
lists
。我希望当用户按下“关注”按钮时向它们添加
userID
。我将它们定义为

...
followers: [],
following: [],
...

据我所知,这两个列表应该是可以增长的,但是当我按下“关注”按钮来关注特定用户时,我收到一条错误消息:

Unsupported operation: Cannot add to a fixed-length list

该错误将我指向了我描述关注用户逻辑的函数,即

void followOneUser(
    User currentUser,
    User user,
    BuildContext context,
  ) async {
    if (currentUser.following.contains(user.id)) {
      currentUser.following.remove(user.id);
      user.followers.remove(currentUser.id);
    } else {
      currentUser.following.add(user.id);
                           ^^^^ // this is what causes the error
      user.followers.add(currentUser.id);
    }

    currentUser = currentUser.copyWith(following: currentUser.following);
    user = user.copyWith(followers: user.followers);

    final result = await ref.watch(userRepoProvider.notifier).followUser(
          currentUser,
          user,
        );

    result.fold(
      (l) => context.showError(
        l,
      ),
      (r) async {
        final res =
            await ref.watch(userRepoProvider.notifier).incrementFollowing(
                  currentUser,
                  user,
                );

        res.fold(
          (l) => context.showError(
            l,
          ),
          (r) => null,
        );
      },
    );
  }

我检查了

following
中如何描述
followers
UserModel
字段,但我无法弄清楚它们在哪里被定义为
ungrowable Lists
。请帮我解决这个问题。

提前谢谢您

flutter list dart aws-amplify
1个回答
0
投票

您面临的问题似乎与 Flutter 中 UserModel 类中使用的列表类型有关。错误消息“不支持的操作:无法添加到固定长度列表”表示列表

followers
following
被视为固定长度列表,一旦用 a 初始化,就不允许添加或删除元素。具体长度。

要解决此问题,您需要确保 UserModel 类中的列表

followers
following
被初始化为可增长列表。以下是修改 UserModel 类以使用可增长列表的方法:

class UserModel {
  List<String> followers = [];
  List<String> following = [];

  UserModel({
    required this.followers,
    required this.following,
  });

  UserModel copyWith({
    List<String>? followers,
    List<String>? following,
  }) {
    return UserModel(
      followers: followers ?? this.followers,
      following: following ?? this.following,
    );
  }
}

通过将

followers
following
列表定义为
List<String>
而不指定固定长度,您可以确保它们是可增长的列表,可以在添加或删除元素时动态调整其大小。

进行此更改后,您应该能够将元素添加到

following
followers
列表,而不会遇到“不支持的操作:无法添加到固定长度列表”错误。

© www.soinside.com 2019 - 2024. All rights reserved.