问题描述
我正在实现一个简单的聊天屏幕,其中列出了消息,并具有要发送的文本框和按钮。
我有以下状态:
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)甚至错误或加载状态显示消息-可能正在显示缓存。
- 将
ChatState
设为唯一状态,并将其中的所有内容都推入。好像是反模式。 - 将
chat
,messages
和users
放在ChatState
中,以便所有状态都有它们。但是,每个状态都有一个庞大的长构造函数,而且确实很冗长,特别是因为此屏幕将变得更加复杂。
我现在要使用2,但这真的是最好的方法吗?我是否以正确的方式使用bloc_library
?
解决方法
由于帖子评论中的建议似乎合理,因此我将其移至此处:
如果我们逐步考虑以下业务逻辑:
- 用户进入屏幕,他看到加载指示符(数据在此处加载)
- 如果没有错误,那么他现在将看到一个视图,其中包含先前提取的所有数据
- 他可以按下按钮/拉动以刷新数据
在这种情况下,我建议向showLoading
状态添加一个ChatSuccess
布尔值。这样,您可以同时显示数据和旋转指示器。
具有状态的流如下:
ChatInProgress -> ChatSuccess(firstData,showLoading: false) -> (pull to refresh) -> ChatSuccess(firstData,showLoading: true) -> ChatSuccess(secondData,showLoading: false)