[英]Flutter how to migrate this BLoC old version code to Bloc new version
我必須如何在 bloc v.8 中編寫此代碼 我不知道我如何看到一些搜索但我不明白這是我的類代碼他們給我錯誤 => StateError (Bad state: add(DoFetchEvent) was called without a registered事件處理程序。確保通過 on((event, emit) {...}) 注冊一個處理程序:
class PostBloc extends Bloc<PostEvent, PostState> {
PostRepository repo;
PostBloc(PostState initialState, this.repo) : super(initialState);
Stream<PostState> mapEventToState(PostEvent event) async* {
if (event is DoFetchEvent) {
yield LoadingState();
try {
var posts = await repo.fetchPosts();
yield FetchSuccess(posts: posts);
} catch (e) {
yield ErrorState(message: e.toString());
}
}
}
}
import 'package:equatable/equatable.dart';
class PostEvent extends Equatable {
@override
List<Object?> get props => [];
}
class DoFetchEvent extends PostEvent {}
class PostState extends Equatable {
@override
List<Object?> get props => [];
}
class InitialState extends PostState {}
class LoadingState extends PostState {}
class FetchSuccess extends PostState {
List<PostModel> posts;
FetchSuccess({required this.posts});
}
class ErrorState extends PostState {
String message;
ErrorState({required this.message});
}
void main() {
runApp(MaterialApp(
home: BlocProvider(
create: (context) => PostBloc(InitialState(), PostRepository()),
child: MyApp(),
),
));
}
您可以直接在super
構造函數中設置InitialState
,而無需像這樣手動傳遞它。
PostBloc(this.repo) : super(InitialState()) {
on<DoFetchEvent>(_onDoFetchEvent);
}
然后你不再在 BlocProvider 中傳入任何BlocProvider
BlocProvider<PostBloc>(
create: (BuildContext context) => PostBloc(PostRepository()),
...
然后,您的mapEventToState
被替換為采用相關event
的方法,以及一個Emitter<PostState>
為 arguments。然后yield
在該方法中被替換為emit
。
你的整個 class 看起來像這樣。
PostBloc(this.repo) : super(InitialState()) {
on<DoFetchEvent>(_onDoFetchEvent);
}
_onDoFetchEvent(
DoFetchEvent event,
Emitter<PostState> emit,
) async {
emit(LoadingState());
try {
var posts = await repo.fetchPosts();
emit(FetchSuccess(posts: posts));
} catch (e) {
emit(ErrorState(message: e.toString()));
}
}
}
應該這樣做。
除此之外,您可能會在 state 類上收到關於must_be_immutable的 linter 警告,因為PostState
擴展Equatable
。
因此,我建議將所有PostState
參數設為final
參數,並將 Equatable 中的props
覆蓋添加到您的Equatable
類中。
class ErrorState extends PostState {
final String message;
ErrorState({required this.message});
@override
List<Object?> get props => [message];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.