Flutter bloc migration due to mapEventToState is not working - flutter

I am following the migration to the new bloc 8.0.0. I am trying to remove the mapEventToState but I am having a difficulty in doing so. Can you help me how to do it. I have tried it below but it won't work.
Old code:
class SignInBloc extends Bloc<SignInEvent, SignInState> {
final AuthenticationRepository authenticationRepository;
final UserDataRepository userDataRepository;
SignInBloc(
{required this.authenticationRepository,
required this.userDataRepository})
: super(SignInInitialState());
SignInState get initialState => SignInInitialState();
#override
Stream<SignInState> mapEventToState(
SignInEvent event,
) async* {
if (event is SignInWithGoogle) {
yield* mapSignInWithGoogleToState();
}
}
Stream<SignInState> mapSignInWithGoogleToState() async* {
yield SignInWithGoogleInProgressState();
try {
String res = await authenticationRepository.signInWithGoogle();
yield SignInWithGoogleCompletedState(res);
} catch (e) {
print(e);
yield SignInWithGoogleFailedState();
}
}
...
Migration code (does not work):
class SignInBloc extends Bloc<SignInEvent, SignInState> {
final AuthenticationRepository authenticationRepository;
final UserDataRepository userDataRepository;
SignInBloc(
{required this.authenticationRepository,
required this.userDataRepository})
: super(SignInInitialState())
{
SignInState get initialState => SignInInitialState();
on<SignInWithGoogle>((event, emit) => emit(mapSignInWithGoogleToState()));
}
Stream<SignInState> mapSignInWithGoogleToState() async* {
yield SignInWithGoogleInProgressState();
try {
String res = await authenticationRepository.signInWithGoogle();
yield SignInWithGoogleCompletedState(res);
} catch (e) {
print(e);
yield SignInWithGoogleFailedState();
}
}
...

Your issue is that mapSignInWithGoogleToState() is returning a Stream of States, but the new structure needs explicit invocations of emit each time a new state needs to be emitted.
class SignInBloc extends Bloc<SignInEvent, SignInState> {
final AuthenticationRepository authenticationRepository;
final UserDataRepository userDataRepository;
SignInBloc({required this.authenticationRepository,
required this.userDataRepository})
: super(SignInInitialState()) {
on<SignInWithGoogle>(mapSignInWithGoogleToState);
}
Future<void> mapSignInWithGoogleToState(
SignInWithGoogle event,
Emitter<SignInState> emit,
) async {
emit(SignInWithGoogleInProgressState());
try {
String res = await authenticationRepository.signInWithGoogle();
emit(SignInWithGoogleCompletedState(res));
} catch (e) {
print(e);
emit(SignInWithGoogleFailedState());
}
}
}
Here is some more information as to "why?": https://bloclibrary.dev/#/migration?id=rationale-8

The getter does not belong in the constructor body and I guess it isn't really needed anymore. You could solve the problem like this:
class SignInBloc extends Bloc<SignInEvent, SignInState> {
final AuthenticationRepository authenticationRepository;
final UserDataRepository userDataRepository;
SignInBloc({required this.authenticationRepository,
required this.userDataRepository})
: super(SignInInitialState()) {
on<SignInWithGoogle>(_handleSignInWithGoogleEvent);
}
Future<void> _handleSignInWithGoogleEvent(
SignInWithGoogle event,
Emitter<SignInState> emit,
) async {
// TODO do your thing and create and emit the SignInWithGoogleState
emit(SignInWithGoogleState());
}
}
Be careful, the events in bloc v8 are not handled sequentially anymore, but concurrently. Give this blog post a read: https://verygood.ventures/blog/how-to-use-bloc-with-streams-and-concurrency

Related

how to mock the state of a StateNotifierProvider flutter

my test is throwing an exception because there is a StateNotifierProvider inside which is not overridden. for a regular Provider, i can override it using providerContainer, but for the state of a stateNotifierProvider, I don't know how to do it. I tried my best but I reached the limit of my best. I already saw this and this but it didn't help.
Appreciate much if someone could help me out of this. Thanks
My service File
class ReportService {
final Ref ref;
ReportService({
required this.ref,
});
Future<void> testReport() async {
//* How can i override this provider ?
final connection = ref.read(connectivityServiceProvider);
if (connection) {
try {
await ref.read(reportRepositoryProvider).testFunction();
} on FirebaseException catch (e, st) {
ref.read(errorLoggerProvider).logError(e, st);
throw Exception(e.message);
}
} else {
throw Exception('Check internet connection...');
}
}
}
final reportServiceProvider = Provider<ReportService>((ref) => ReportService(
ref: ref,
));
My test file
void main() {
WidgetsFlutterBinding.ensureInitialized();
final reportRepository = MockReportRepository();
ReportService makeReportService() {
final container = ProviderContainer(overrides: [
reportRepositoryProvider.overrideWithValue(reportRepository),
]);
addTearDown(container.dispose);
return container.read(reportServiceProvider);
}
test('test test', () async {
//How to stub the connectivityServiceProvider here ?
when(reportRepository.testFunction)
.thenAnswer((invocation) => Future.value());
final service = makeReportService();
await service.testReport();
verify(reportRepository.testFunction).called(1);
});
My StateNotifierProvider
class ConnectivityService extends StateNotifier<bool> {
ConnectivityService() : super(false);
}
final connectivityServiceProvider =
StateNotifierProvider<ConnectivityService, bool>(
(ref) => ConnectivityService());

Flutter Bloc cancel running event when a new one is recieved

I have the follwing Bloc
class DeviceBloc extends Bloc<DeviceEvent, DeviceState> {
DataRepository repository;
DeviceBloc({#required this.repository}) : super(DeviceInitialState()) {
on<FetchDevicesEvent>(onFetchResources);
}
Future<void> onFetchResources(
FetchDevicesEvent event, Emitter<DeviceState> emit) async {
emit.call(DeviceLoadingState());
try {
List<DeviceResource> devices = await repository.getResources(event.type);
emit.call(DeviceLoadedState(devices: devices));
} catch (e) {
emit.call(DeviceErrorState(message: e.toString()));
}
}
}
When FetchDevicesEvent event is triggered it starts a long running task, if additional FetchDevicesEvent events are recieved before the running task is completed the wrong result are returned to the caller. How can I suspend the awaited task and always start a new as soon as a new FetchDevicesEvent is recieved?
Found the solution myself by using transformer: restartable() from bloc_concurrency package
class DeviceBloc extends Bloc<DeviceEvent, DeviceState> {
DataRepository repository;
DeviceBloc({#required this.repository}) : super(DeviceInitialState()) {
on<FetchDevicesEvent>(
onFetchResources,
transformer: restartable(),
);
}
Future<void> onFetchResources(
FetchDevicesEvent event, Emitter<DeviceState> emit) async {
emit.call(DeviceLoadingState());
try {
final List<DeviceResource> devices =
await repository.getResources(event.type);
emit.call(DeviceLoadedState(devices: devices));
} catch (e) {
emit.call(DeviceErrorState(message: e.toString()));
}
}
}

flutter how to yield to a stream of bloc?

Hi I'm new to flutter and dart. I'm following a lesson on internet which is practicing to use bloc to control states. First lesson is after showing appStart animation, turn to a login page.
the lesson was using 'mapEventToState':
class AuthenticationBloc extends Bloc<AuthenticationEvent, AuthenticationState> {
final UserRepository? _userRepository;
AuthenticationBloc({UserRepository? userRepository})
: assert(userRepository != null),
_userRepository = userRepository, super(Uninitialized());
#override
Stream<AuthenticationState> mapEventToState(
AuthenticationEvent event,
) async* {
if (event is AppStarted) {
yield* _mapAppStartedToState();
} else if (event is LoggedIn) {
yield* _mapLoggedInToState();
} else if (event is LoggedOut) {
yield* _mapLoggedOutToState();
}
Stream<AuthenticationState> _mapAppStartedToState() async* {
log('_mapAppStartedToState is running.');
try {
final bool? isSigned = await _userRepository?.isSignedIn();
if (isSigned != null) {
if (isSigned) {
final String? name = await _userRepository?.getUser();
yield Authenticated(name);
}
else {
yield Unauthenticated();
}
}
} catch (_) {
yield Unauthenticated();
}
}
Stream<AuthenticationState> _mapLoggedInToState() async* {
log('_mapLoggedInToState is running.');
yield Authenticated(await _userRepository?.getUser());
}
Stream<AuthenticationState> _mapLoggedOutToState() async* {
log('_mapLoggedOutToState is running.');
yield Unauthenticated();
_userRepository?.signOut();
}
}
turns out 'mapEventToState' was removed.
According to this page(https://github.com/felangel/bloc/issues/2526), I try to use on< event > instead:
#override
AuthenticationBloc({UserRepository? userRepository})
: assert(userRepository != null, 'userRepository == null'),
_userRepository = userRepository,
super(Uninitialized()) {
log('AuthenticationBloc is running.');
on<AppStarted>(_appStarted);
on<LoggedIn>(_loggedIn);
on<LoggedOut>(_loggedOut);
}
Stream<AuthenticationState> _appStarted(AuthenticationEvent event, Emitter<AuthenticationState> emit) async* {
log('_appStarted is running.');
yield* _mapAppStartedToState();
}
But it didn't work. Even log('_appStarted is running.'); didn't show at console.
I tried to change type and aync*. It would show console log if _appStarted isn't aync.
void _appStarted(AuthenticationEvent event, Emitter<AuthenticationState> emit) {
log('_appStarted is running.');
// yield* _mapAppStartedToState();
}
However, it can't yield to stream as _appStarted isn't aync. Makes me confused.
Please let me know if I got some misunderstand about bloc and stream. Happy to see any solution or advise.
You no longer need your one function per event, because you already have it:
void _appStarted(AuthenticationEvent event, Emitter<AuthenticationState> emit) {
log('_appStarted is running.');
try {
final bool? isSigned = await _userRepository?.isSignedIn();
if (isSigned != null) {
if (isSigned) {
final String? name = await _userRepository?.getUser();
emit(Authenticated(name));
}
else {
emit(Unauthenticated());
}
}
} catch (_) {
emit(Unauthenticated());
}
}
If you want to delegate this to another function, just remove the stream return value and pass the emitter.

Succeeding Bloc are not working after latest Bloc migration

I am using a MultiBlocProvider which is working for all Bloc before I migrate it to v8.0.1. Now, only the first Bloc (SignInBloc) is working.
This is on my main.dart
return MultiBlocProvider(
providers: [
BlocProvider<SignInBloc>(
create: (context) => SignInBloc(
authenticationRepository: authenticationRepository,
userDataRepository: userDataRepository,
),
),
BlocProvider<SignUpBloc>(
create: (context) => SignUpBloc(
authenticationRepository: authenticationRepository,
userDataRepository: userDataRepository,
),
),
Edit: here is my SignInBloc
SignInBloc(
{required this.authenticationRepository,
required this.userDataRepository})
: super(SignInInitialState()) {
on<CheckIfSignedInEvent>(mapCheckIfSignedInEventToState);
}
Future<void> mapCheckIfSignedInEventToState(
CheckIfSignedInEvent event,
Emitter<SignInState> emit,
) async {
try {
bool isSignedIn = await authenticationRepository.checkIfSignedIn();
if (isSignedIn) {
emit(CheckIfSignedInEventCompletedState(true));
} else {
emit(CheckIfSignedInEventCompletedState(false));
}
} catch (e) {
print(e);
emit(CheckIfSignedInEventFailedState());
}
}
I am not sure what to show but here is my SignUpBloc which is similar to my SignInBloc
SignUpBloc(
{required this.authenticationRepository,
required this.userDataRepository})
: super(SignUpInitialState()) {
on<SignUpWithGoogle>(mapSignUpWithGoogleEventToState);
}
Stream<SignUpState> mapSignUpWithGoogleEventToState(
SignUpWithGoogle event,
Emitter<SignUpState> emit,
) async* {
emit(SignUpInProgressState());
try {
User? checkUser = await authenticationRepository.checkIfUserExists();
if (checkUser != null) {
emit(SignUpWithGoogleInitialExistState());
} else {
bool checkDup =
await authenticationRepository.checkIfUserDup(event.name);
if (checkDup == true) {
emit(SignUpWithNameExistState());
} else {
User firebaseUser = await authenticationRepository.signUpWithGoogle();
emit(SignUpWithGoogleInitialCompletedState(firebaseUser));
}
}
} catch (e) {
print(e);
emit(SignUpWithGoogleInitialFailedState());
}
}
My main.dart will call the splash screen which has the declaration of the bloc
late SignInBloc signInBloc;
late SignUpBloc signupBloc;
class _SplashScreenState extends State<SplashScreen> {
#override
void initState() {
super.initState();
signInBloc = BlocProvider.of<SignInBloc>(context);
signupBloc = BlocProvider.of<SignUpBloc>(context);
What I tried to do it to put alot of Print statement in order to check which part is getting called but I don't get why the SignUpBloc is not getting called anymore. Please help. Thanks!
Edit: I tried to debug.
This will trigger my SignInBloc. I'm able to listen to my SignInBloc.
signInBloc.add(CheckIfSignedInEvent());
This should trigger my SignUpBloc. But it doesn't do anything similar to my SignInBloc.
signupBloc.add(SignUpWithGoogle(name: selectedName));
Here's both of my events for comparison:
class CheckIfSignedInEvent extends SignInEvent {
#override
String toString() => 'CheckIfSignedInEvent';
}
class SignUpWithGoogle extends SignUpEvent {
final String name;
SignUpWithGoogle({required this.name});
#override
String toString() => 'SignUpWithGoogleEvent';
}
This is the part where I listen to the states which is both in my splash screen. Only signInBloc is able to listen.
signupBloc.stream.listen((state) {
print('BLOC: signupBloc splash screen init : $state');
});
signInBloc.stream.listen((state) {
print('BLOC: signinBloc splash screen init : $state');
});
It turns out that changing the Stream to Future will fix my issue. async* should also be changed to async
Future<void> mapSignUpWithGoogleEventToState(
SignUpWithGoogle event,
Emitter<SignUpState> emit,
) async {
emit(SignUpInProgressState());
try {
User? checkUser = await authenticationRepository.checkIfUserExists();
if (checkUser != null) {
emit(SignUpWithGoogleInitialExistState());
} else {
bool checkDup =
await authenticationRepository.checkIfUserDup(event.name);
if (checkDup == true) {
emit(SignUpWithNameExistState());
} else {
User firebaseUser = await authenticationRepository.signUpWithGoogle();
emit(SignUpWithGoogleInitialCompletedState(firebaseUser));
}
}
} catch (e) {
print(e);
emit(SignUpWithGoogleInitialFailedState());
}
}

Handling Errors with Dio/bloc Flutter

I need a good way to handle errors while I'm Using Dio requests.
Can I do it in one class and pass the dio request throw it ?
and it should return a response with the error .
I am posting my generalized network bloc here, which can be reused any number of time, any where. also, It uses dio using API repository , exceptional and error handling.
class NetworkBloc extends Bloc<NetworkEvent, NetworkState> {
NetworkBloc() : super(NetworkRequestInitial());
#override
Stream<NetworkState> mapEventToState(
NetworkEvent event,
) async* {
yield NetworkRequestInitiated();
if (event is NetworkCallEvent) {
RequestType requestType = event.requestType;
if (requestType == RequestType.GET) {
yield* fetchData(event);
} else if (requestType == RequestType.POST) {
yield* uploadDataAndStoreResult(event);
}
}
}
Stream<NetworkState> fetchData(NetworkCallEvent event) async* {
Response response;
try {
yield NetworkRequestLoading();
response =
await event.apiRepository.sendGetRequest(event.url, event.request);
if (response.statusCode == 200) {
yield NetworkRequestLoaded(response: response);
} else {
Map jsonResponse = jsonDecode(response.data);
yield NetworkRequestFailure(message: jsonResponse['message']);
}
} catch (e) {
yield NetworkRequestFailure(
message: NetworkUtils.getErrorMessageAccordingToError(e));
}
}
Stream<NetworkState> uploadDataAndStoreResult(NetworkCallEvent event) async* {
Response response;
try {
yield NetworkRequestLoading();
if (event.request != null) {
if (event.isHeadersNeeded) {
response = await event.apiRepository.sendPostRequestWithHeader(
event.url,
request: event.request,
);
} else {
response = await event.apiRepository.sendPostRequest(
event.url,
event.request,
);
}
} else {
response = await event.apiRepository
.sendPostRequestWithoutBodyParameters(event.url);
}
if (response.statusCode == 200) {
saveDataAccordingToCacheMechanism(event, response);
yield NetworkRequestLoaded(response: response);
} else {
Map jsonResponse = jsonDecode(response.data);
yield NetworkRequestFailure(message: jsonResponse['message']);
}
} catch (e) {
yield NetworkRequestFailure(
message: NetworkUtils.getErrorMessageAccordingToError(e));
}
}
void saveDataAccordingToCacheMechanism(
NetworkCallEvent event, Response response) async {
if (event.cacheMechanism == CacheMechanism.SharePreferences) {
Hive.box(ConstUtils.dbName)
.put(event.keyForSharedPreferences, response.data.toString());
} else if (event.cacheMechanism == CacheMechanism.Database) {}
}
}
I am also adding states and events to make it more easy to understand.
class NetworkCallEvent extends NetworkEvent {
final String request;
final dynamic url;
final RequestType requestType;
final CacheMechanism cacheMechanism;
final String keyForSharedPreferences;
final APIRepository apiRepository;
final bool isHeadersNeeded;
NetworkCallEvent(
{#required this.url,
this.request,
this.isHeadersNeeded = false,
#required this.requestType,
#required this.apiRepository,
#required this.cacheMechanism,
this.keyForSharedPreferences});
#override
List<Object> get props => [
this.url,
this.request,
this.requestType,
this.cacheMechanism,
this.keyForSharedPreferences,
this.apiRepository
];
}
Network_states:
class NetworkRequestInitial extends NetworkState {}
class NetworkRequestInitiated extends NetworkState {}
class NetworkRequestLoading extends NetworkState {}
class NetworkRequestLoaded extends NetworkState {
final dynamic response;
NetworkRequestLoaded({this.response});
#override
List<Object> get props => [this.response];
}
class NetworkRequestFailure extends NetworkState {
final String message;
NetworkRequestFailure({this.message});
#override
List<Object> get props => [this.message];
}
You can easily send request in JSON and get Response in dynamic, which you can convert to appropriate object using json.decode().