减少flutter_bloc库中状态的详细程度

问题描述

我正在实现一个简单的聊天屏幕,其中列出了消息,并具有要发送的文本框和按钮。

我有以下状态:

abstract class ChatState extends Equatable {
  const ChatState();

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

class ChatFailure extends ChatState {
  final Exception reason;
  const ChatFailure({this.reason});

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

class ChatInProgress extends ChatState {}

class ChatSuccess extends ChatState {
  final Chat chat;
  final List<Message> messages;
  final Map<int,User> users;

  const ChatSuccess({
    @required this.chat,@required this.messages,@required this.users,});

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

但是,我现在希望能够以所有状态(如果不是null)甚至错误或加载状态显示消息-可能正在显示缓存。

看来我有两种方法可以做到,但似乎都不是一个好选择:

  1. ChatState设为唯一状态,并将其中的所有内容都推入。好像是反模式。
  2. chatmessagesusers放在ChatState中,以便所有状态都有它们。但是,每个状态都有一个庞大的长构造函数,而且确实很冗长,特别是因为此屏幕将变得更加复杂。

我现在要使用2,但这真的是最好的方法吗?我是否以正确的方式使用bloc_library

解决方法

由于帖子评论中的建议似乎合理,因此我将其移至此处:

如果我们逐步考虑以下业务逻辑:

  1. 用户进入屏幕,他看到加载指示符(数据在此处加载)
  2. 如果没有错误,那么他现在将看到一个视图,其中包含先前提取的所有数据
  3. 他可以按下按钮/拉动以刷新数据

在这种情况下,我建议向showLoading状态添加一个ChatSuccess布尔值。这样,您可以同时显示数据和旋转指示器。

具有状态的流如下:

ChatInProgress -> ChatSuccess(firstData,showLoading: false) -> (pull to refresh) -> ChatSuccess(firstData,showLoading: true) -> ChatSuccess(secondData,showLoading: false)