Flutter如何将此BLoC旧版本代码迁移到BLoC新版本



我必须如何在blockv.8中编写此代码。我不知道我是如何看到一些搜索的,但我不理解,这是我的类代码,他们给了我错误=>StateError(错误状态:在没有注册事件处理程序的情况下调用了add(DoFetchEvent(。请确保通过((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<PostBloc>(
create: (BuildContext context) => PostBloc(PostRepository()),
...

然后,您的mapEventToState将被一个以相关eventEmitter<PostState>为参数的方法所替换。然后在该方法中将CCD_ 7替换为CCD_。

你全班同学都会是这个样子。

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()));
}
}
}

这样就可以了。

除此之外,由于PostState扩展了Equatable,您可能会在状态类上收到关于must_be_invariable的linter警告。

因此,我建议将所有PostState参数设置为final,并将Equatable中的props覆盖添加到您的状态类中。

class ErrorState extends PostState {
final String message;
ErrorState({required this.message});
@override
List<Object?> get props => [message];
}

最新更新