我必須如何在 bloc v.8 中撰寫此代碼事件處理程式。確保通過 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(),
),
));
}
uj5u.com熱心網友回復:
您可以InitialState直接在super建構式中設定您的,而無需像這樣手動傳遞它。
PostBloc(this.repo) : super(InitialState()) {
on<DoFetchEvent>(_onDoFetchEvent);
}
然后你不再以任何狀態通過BlocProvider
BlocProvider<PostBloc>(
create: (BuildContext context) => PostBloc(PostRepository()),
...
然后你的mapEventToState被替換為一個接受相關的方法event,和一個Emitter<PostState>作為引數。yield然后在方法中被替換為emit。
你的整個班級會是這樣的。
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()));
}
}
}
那應該這樣做。
除此之外,您可能會在狀態類上收到有關must_be_immutablePostState的 linter 警告,因為extend Equatable。
所以我建議制作所有PostState引數final并將props覆寫添加Equatable到您的狀態類中。
class ErrorState extends PostState {
final String message;
ErrorState({required this.message});
@override
List<Object?> get props => [message];
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/442450.html
