'how to transfer this code in flutter_bloc V7 to flutter_bloc V8?
the problem is that I want to transfer this code from bloc 7 to bloc 8 using emit and on<RunLongRunningStreamedEvent and i know that mapEventtoState no longer exisits
import 'package:bloc/bloc.dart';
import 'data/repository/irepository.dart';
import 'home_event.dart';
import 'home_state.dart';
class HomeBloc extends Bloc<HomeEvent, HomeState> {
IRepository _repository;
HomeBloc(this._repository) : super(HomeState.initail());
@override
HomeState get initialState => HomeState.initail();
// I want to replace this stream with a new version and change all the bloc
Stream<HomeState> mapEventToState(
HomeEvent event,
) async* {
if (event is ClearError) {
yield state.rebuild((b) => b..error = "");
}
if (event is GetHomeData) {
try {
yield state.rebuild((b) => b
..isLoading = true
..error = ""
..isSucessGet = false
..GetDataHome = null);
final slidersData = await _repository.getHomeData();
yield state.rebuild((b) => b
..isLoading = false
..error = ""
..isSucessGet = true
..GetDataHome.replace(slidersData));
} catch (e) {
print('profile Error $e');
yield state.rebuild((b) => b
..isLoading = false
..isSucessGet = false
..error = "Please check network connection"
..GetDataHome = null);
}
}
Solution 1:[1]
You didn't share the full implementation of your HomeBloc so this might have a few errors but it should get you pretty close. Basically, you no longer have to manually call yield. You just create methods with the relevant event and Emitter<HomeState> (or whatever the relevant State of your bloc is) as the arguments, and call the method in the on<YourEvent> portion of the constructor.
class HomeBloc extends Bloc<HomeEvent, HomeState> {
IRepository _repository;
HomeBloc(this._repository) : super(HomeState.initail()) {
on<ClearError>(_onClearError);
on<GetHomeData>(_onClearError);
}
Future<void> _onClearError(
ClearError event,
Emitter<HomeState> emit,
) {
emit(state.rebuild((b) => b..error = ""));
}
Future<void> _onGetHomeData(
GetHomeData event,
Emitter<HomeState> emit,
) async {
try {
emit(state.rebuild((b) => b
..isLoading = true
..error = ""
..isSucessGet = false
..GetDataHome = null));
final slidersData = await _repository.getHomeData();
emit(state.rebuild((b) => b
..isLoading = false
..error = ""
..isSucessGet = true
..GetDataHome.replace(slidersData)));
} catch (e) {
print('profile Error $e');
emit(state.rebuild((b) => b
..isLoading = false
..isSucessGet = false
..error = "Please check network connection"
..GetDataHome = null));
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Loren.A |
