【问题标题】:Error: type 'List<User>' is not a subtype of type 'User' in Flutter, using Bloc 8.0.1错误:使用 Bloc 8.0.1,类型“List<User>”不是 Flutter 中“User”类型的子类型
【发布时间】:2022-01-03 08:09:38
【问题描述】:

我是 Flutter 和 Bloc 的新手,我正在尝试实现一个约会应用程序,该应用程序涉及滑动用户喜欢/不喜欢。我正在使用 Bloc v8.0.1,如果用户滑动,我在 Bloc 类中遇到困难。我想从列表中删除用户。目前,我在emit(SwipeLoaded(users: List.from(state.props)..remove(event.user))); 代码行中收到错误'type 'List ' is not a subtype of type 'User''。我尝试了不同的方法来访问该列表,但我想不出一种可行的方法。我已经包含了我能想到的所有相关代码,任何帮助将不胜感激!

集团类

class SwipeBloc extends Bloc<SwipeEvent, SwipeState> {
    SwipeBloc() : super(SwipeLoading()) {
        on<SwipeEvent>(
          (event, emit) async {
            if (event is SwipeLeftEvent) {
              if (state is SwipeLoaded) {
                try {
                  emit(SwipeLoaded(users: List.from(state.props)..remove(event.user)));
                } catch (_) { }
              }
            } 

状态类

class SwipeLoading extends SwipeState {}

class SwipeLoaded extends SwipeState {
  final List<User> users;

  const SwipeLoaded({
    required this.users,
});

  @override
  List<Object> get props => [users];
}

事件类

class SwipeLeftEvent extends SwipeEvent {
  final User user;

  SwipeLeftEvent({
    required this.user,
  });

  @override
  List<Object> get props => [user];
}

【问题讨论】:

    标签: flutter dart bloc


    【解决方案1】:

    我不完全确定这是否是您的错误的根源,但在我看来可疑的一件事是这段代码:

    class SwipeLoaded extends SwipeState {
      final List<User> users;
    
      const SwipeLoaded({
        required this.users,
      });
    
      @override
      List<Object> get props => [users];
    }
    

    这里的 getter props 实际上返回了一个 List&lt;List&lt;User&gt;&gt;,我怀疑这可能不是您想要的。

    这就是我认为你想要的代码:

    class SwipeLoaded extends SwipeState {
      final List<User> users;
    
      const SwipeLoaded({
        required this.users,
      });
    
      @override
      List<User> get props => [...users];
    }
    

    【讨论】:

    • 这似乎解决了它!非常感谢您的帮助
    • 一点一般建议,尽量避免使用Objectdynamic 类型。如果 props 有 List&lt;User&gt; 返回类型,类型系统会使错误更加明显。
    猜你喜欢
    • 2020-09-01
    • 2022-12-02
    • 2021-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多