有时候,我们在开发中使用 Bloc 模式来管理状态,并且可能需要将小部件添加到列表中。如果 Bloc 没有成功将小部件添加到列表中,则可能是因为我们在 Bloc 的状态中没有正确地更新列表。以下是解决方法的示例代码,假设我们正在尝试将字符串添加到列表中:
class MyBlocState extends Equatable {
final List myList;
...
2.更新状态类中的构造函数,将 myList 设置为空列表:
MyBlocState({List myList = const []}): myList = myList ?? [];
3.在 Bloc 的存储器中初始化 状态 以 构造函数的创建:
MyBloc() : super(MyBlocState());
@override
Stream mapEventToState(MyBlocEvent event) async* {
if (event is AddToListEvent) {
final currentList = state.myList;
yield state.copyWith(myList: [...currentList, event.newItem]);
}
}
这将使用输入的 newItem 来更新列表,并正确地将其添加到状态中。这样,你就可以在小部件中正确地访问和显示列表了。