To preface, I am new to flutter, I just finished a 37 hour course on YouTube but I am still learning.
Anyway, I am trying to use Bloc to handle navigation in the beginning and end of my app, so logging in, registering, forgot password, verifying email, and logging out. Everything else is handled by navigator routes. I have followed this YouTube tutorial and my code structure almost matches his, but it say own app so its not exactly the same)
I can login, go to the register screen, and forgot password screen, but after I login, and then go to logout, it will log me out, but then I can’t do anything else until I hot restart.
Here is my main.dart
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:manebenefitsstudent/constants/routes.dart';
import 'package:manebenefitsstudent/constants/theme_data.dart';
import 'package:manebenefitsstudent/helpers/loading/loading_screen.dart';
import 'package:manebenefitsstudent/services/auth/bloc/auth_bloc.dart';
import 'package:manebenefitsstudent/services/auth/firebase_auth_provider.dart';
import 'package:manebenefitsstudent/views/categories/activities_view.dart';
import 'package:manebenefitsstudent/views/categories/categories_home_view.dart';
import 'package:manebenefitsstudent/views/categories/health_and_beauty_view.dart';
import 'package:manebenefitsstudent/views/categories/restaurants_view.dart';
import 'package:manebenefitsstudent/views/categories/retail_view.dart';
import 'package:manebenefitsstudent/views/categories/services_view.dart';
import 'package:manebenefitsstudent/views/categories/seven_points_view.dart';
import 'package:manebenefitsstudent/views/settings_view.dart';
import 'package:manebenefitsstudent/views/login_view.dart';
import 'package:manebenefitsstudent/views/register_view.dart';
import 'package:manebenefitsstudent/views/forgot_password_view.dart';
import 'package:manebenefitsstudent/views/verify_email_view.dart';
import 'services/auth/bloc/auth_event.dart';
import 'services/auth/bloc/auth_state.dart';
import 'services/auth/bloc/auth_handler.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(
BlocProvider<AuthBloc>(
create: (context) => AuthBloc(FirebaseAuthProvider()),
child: const MyApp(),
),
);
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: AppTheme.theme,
home: const HomePage(),
routes: {
categoriesHomeViewRoute: (context) => const CategoriesHomeView(),
activitiesViewRoute: (context) => const ActivitiesView(),
healthAndBeautyViewRoute: (context) => const HealthAndBeautyView(),
restaurantsViewRoute: (context) => const RestaurantsView(),
retailViewRoute: (context) => const RetailView(),
servicesViewRoute: (context) => const ServicesView(),
sevenPointsViewRoute: (context) => const SevenPointsView(),
settingsViewRoute: (context) => const SettingsView(),
loginViewRoute: (context) => const LoginView(),
verifyEmailViewRoute: (context) => const VerifyEmailView(),
registerViewRoute: (context) => const RegisterView(),
forgotPasswordViewRoute: (context) => const ForgotPasswordView(),
},
);
}
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
context.read<AuthBloc>().add(const AuthEventInitialize());
return BlocConsumer<AuthBloc, AuthState>(
listener: (context, state) {
if (state.isLoading) {
LoadingScreen().show(
context: context,
text: state.loadingText ?? 'Please wait a moment',
);
} else {
LoadingScreen().hide();
}
},
builder: (context, state) {
return const AuthHandler();
},
);
}
}
My Auth Bloc:
import 'package:bloc/bloc.dart';
import 'package:manebenefitsstudent/services/auth/auth_provider.dart';
import 'auth_event.dart';
import 'auth_state.dart';
class AuthBloc extends Bloc<AuthEvent, AuthState> {
AuthBloc(AuthProvider provider)
: super(const AuthStateUninitialized(isLoading: true)) {
on<AuthEventShouldRegister>((event, emit) {
print("Event: AuthEventShouldRegister");
emit(const AuthStateRegistering(
exception: null,
isLoading: false,
));
});
on<AuthEventForgotPassword>((event, emit) async {
print("Event: AuthEventForgotPassword");
emit(const AuthStateForgotPassword(
exception: null,
hasSentEmail: false,
isLoading: false,
));
final email = event.email;
if (email == null) {
return;
}
emit(const AuthStateForgotPassword(
exception: null,
hasSentEmail: false,
isLoading: true,
));
bool didSendEmail;
Exception? exception;
try {
await provider.sendPasswordReset(toEmail: email);
didSendEmail = true;
exception = null;
} on Exception catch (e) {
didSendEmail = false;
exception = e;
}
emit(AuthStateForgotPassword(
exception: exception,
hasSentEmail: didSendEmail,
isLoading: false,
));
});
on<AuthEventSendEmailVerification>((event, emit) async {
await provider.sendEmailVerification();
emit(state);
});
on<AuthEventRegister>((event, emit) async {
print("Event: AuthEventRegister");
final email = event.email;
final password = event.password;
try {
await provider.createUser(
email: email,
password: password,
);
await provider.sendEmailVerification();
emit(const AuthStateNeedsVerification(isLoading: false));
} on Exception catch (e) {
emit(AuthStateRegistering(
exception: e,
isLoading: false,
));
}
});
on<AuthEventInitialize>((event, emit) async {
print("Event: AuthEventInitialize");
await provider.initialize();
final user = provider.currentUser;
if (user == null) {
emit(const AuthStateLoggedOut(
exception: null,
isLoading: false,
));
} else if (!user.isEmailVerified) {
emit(const AuthStateNeedsVerification(isLoading: false));
} else {
emit(AuthStateLoggedIn(
user: user,
isLoading: false,
));
}
});
on<AuthEventLogIn>((event, emit) async {
print("Event: AuthEventLogIn");
emit(
const AuthStateLoggedOut(
exception: null,
isLoading: true,
loadingText: 'Please wait while I log you in',
),
);
final email = event.email;
final password = event.password;
try {
final user = await provider.logIn(
email: email,
password: password,
);
if (!user.isEmailVerified) {
emit(const AuthStateNeedsVerification(isLoading: false));
} else {
emit(AuthStateLoggedIn(
user: user,
isLoading: false,
));
}
} on Exception catch (e) {
emit(AuthStateLoggedOut(
exception: e,
isLoading: false,
));
}
});
on<AuthEventLogOut>((event, emit) async {
print("Event: AuthEventLogOut");
try {
await provider.logOut();
emit(
const AuthStateLoggedOut(
exception: null,
isLoading: false,
),
);
} on Exception catch (e) {
emit(
AuthStateLoggedOut(
exception: e,
isLoading: false,
),
);
}
});
}
}
My Auth Handler:
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:manebenefitsstudent/helpers/loading/loading_screen.dart';
import 'package:manebenefitsstudent/services/auth/bloc/auth_bloc.dart';
import 'package:manebenefitsstudent/services/auth/bloc/auth_event.dart';
import 'package:manebenefitsstudent/services/auth/bloc/auth_state.dart';
import 'package:manebenefitsstudent/views/login_view.dart';
import 'package:manebenefitsstudent/views/forgot_password_view.dart';
import 'package:manebenefitsstudent/views/register_view.dart';
import 'package:manebenefitsstudent/views/verify_email_view.dart';
import 'package:manebenefitsstudent/views/categories/categories_home_view.dart';
class AuthHandler extends StatelessWidget {
const AuthHandler({super.key});
@override
Widget build(BuildContext context) {
context.read<AuthBloc>().add(const AuthEventInitialize());
return BlocConsumer<AuthBloc, AuthState>(
listener: (context, state) {
if (state.isLoading) {
LoadingScreen().show(
context: context,
text: state.loadingText ?? 'Please wait a moment',
);
} else {
LoadingScreen().hide();
}
},
builder: (context, state) {
if (state is AuthStateLoggedIn) {
return const CategoriesHomeView();
} else if (state is AuthStateNeedsVerification) {
return const VerifyEmailView();
} else if (state is AuthStateLoggedOut) {
return const LoginView();
} else if (state is AuthStateForgotPassword) {
return const ForgotPasswordView();
} else if (state is AuthStateRegistering) {
return const RegisterView();
} else {
return const Scaffold(
body: Center(child: CircularProgressIndicator()),
);
}
},
);
}
}
My Auth Event:
import 'package:flutter/foundation.dart' show immutable;
@immutable
abstract class AuthEvent {
const AuthEvent();
}
class AuthEventInitialize extends AuthEvent {
const AuthEventInitialize();
}
class AuthEventSendEmailVerification extends AuthEvent {
const AuthEventSendEmailVerification();
}
class AuthEventLogIn extends AuthEvent {
final String email;
final String password;
const AuthEventLogIn(this.email, this.password);
}
class AuthEventRegister extends AuthEvent {
final String email;
final String password;
const AuthEventRegister(this.email, this.password);
}
class AuthEventShouldRegister extends AuthEvent {
const AuthEventShouldRegister();
}
class AuthEventForgotPassword extends AuthEvent {
final String? email;
const AuthEventForgotPassword({this.email});
}
class AuthEventLogOut extends AuthEvent {
const AuthEventLogOut();
}
My Auth State:
import 'package:flutter/foundation.dart' show immutable;
import 'package:manebenefitsstudent/services/auth/auth_user.dart';
import 'package:equatable/equatable.dart';
@immutable
abstract class AuthState {
final bool isLoading;
final String? loadingText;
const AuthState({
required this.isLoading,
this.loadingText = 'Please wait a moment',
});
}
class AuthStateUninitialized extends AuthState {
const AuthStateUninitialized({required bool isLoading})
: super(isLoading: isLoading);
}
class AuthStateRegistering extends AuthState {
final Exception? exception;
const AuthStateRegistering({
required this.exception,
required isLoading,
}) : super(isLoading: isLoading);
}
class AuthStateForgotPassword extends AuthState {
final Exception? exception;
final bool hasSentEmail;
const AuthStateForgotPassword({
required this.exception,
required this.hasSentEmail,
required bool isLoading,
}) : super(isLoading: isLoading);
}
class AuthStateLoggedIn extends AuthState {
final AuthUser user;
const AuthStateLoggedIn({
required this.user,
required bool isLoading,
}) : super(isLoading: isLoading);
}
class AuthStateNeedsVerification extends AuthState {
const AuthStateNeedsVerification({required bool isLoading})
: super(isLoading: isLoading);
}
class AuthStateLoggedOut extends AuthState with EquatableMixin {
final Exception? exception;
const AuthStateLoggedOut({
required this.exception,
required bool isLoading,
String? loadingText,
}) : super(
isLoading: isLoading,
loadingText: loadingText,
);
@override
List<Object?> get props => [exception, isLoading];
}
My Auth Service:
import 'package:manebenefitsstudent/services/auth/auth_provider.dart';
import 'package:manebenefitsstudent/services/auth/auth_user.dart';
import 'package:manebenefitsstudent/services/auth/firebase_auth_provider.dart';
class AuthService implements AuthProvider {
final AuthProvider provider;
const AuthService(this.provider);
factory AuthService.firebase() => AuthService(FirebaseAuthProvider());
@override
Future<AuthUser> createUser({
required String email,
required String password,
}) =>
provider.createUser(
email: email,
password: password,
);
@override
AuthUser? get currentUser => provider.currentUser;
@override
Future<AuthUser> logIn({
required String email,
required String password,
}) =>
provider.logIn(
email: email,
password: password,
);
@override
Future<void> logOut() => provider.logOut();
@override
Future<void> sendEmailVerification() => provider.sendEmailVerification();
@override
Future<void> initialize() => provider.initialize();
@override
Future<void> sendPasswordReset({required String toEmail}) =>
provider.sendPasswordReset(toEmail: toEmail);
}
my login_view:
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:manebenefitsstudent/services/auth/auth_exceptions.dart';
import 'package:manebenefitsstudent/services/auth/bloc/auth_bloc.dart';
import 'package:manebenefitsstudent/services/auth/bloc/auth_event.dart';
import 'package:manebenefitsstudent/services/auth/bloc/auth_state.dart';
import 'package:manebenefitsstudent/utilities/dialogs/error_dialog.dart';
class LoginView extends StatefulWidget {
const LoginView({super.key});
@override
State<LoginView> createState() => _LoginViewState();
}
class _LoginViewState extends State<LoginView> {
late final TextEditingController _email;
late final TextEditingController _password;
@override
void initState() {
_email = TextEditingController();
_password = TextEditingController();
super.initState();
}
@override
void dispose() {
_email.dispose();
_password.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return BlocListener<AuthBloc, AuthState>(
listener: (context, state) async {
if (state is AuthStateLoggedOut) {
if (state.exception is UserNotFoundAuthException ||
state.exception is WrongPasswordAuthException) {
await showErrorDialog(
context,
'Invalid User Credentials, Register new email, or try again.',
);
} else if (state.exception is GenericAuthException) {
await showErrorDialog(
context,
'Something went wrong, please try again.',
);
}
}
},
child: Scaffold(
appBar: AppBar(
title: const Text('Login'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Center(
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('Please Login using your UNA Email!'),
TextField(
controller: _email,
enableSuggestions: false,
autocorrect: false,
keyboardType: TextInputType.emailAddress,
textAlign: TextAlign.center,
decoration: const InputDecoration(
hintText: 'Enter Email here',
),
),
TextField(
controller: _password,
obscureText: true,
enableSuggestions: false,
autocorrect: false,
textAlign: TextAlign.center,
decoration: const InputDecoration(
hintText: 'Enter Password here',
),
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: () async {
final email = _email.text;
final password = _password.text;
print('Login Button Pressed');
context.read<AuthBloc>().add(
AuthEventLogIn(
email,
password,
),
);
},
child: const Text('Login'),
),
const SizedBox(height: 10),
ElevatedButton(
onPressed: () {
print('Forgot Password Button Pressed');
context.read<AuthBloc>().add(
const AuthEventForgotPassword(),
);
},
child: const Text('Forgot Password'),
),
const SizedBox(height: 10),
ElevatedButton(
onPressed: () {
print('Register Button Pressed');
context.read<AuthBloc>().add(
const AuthEventShouldRegister(),
);
},
child: const Text('Register Here'),
),
],
),
),
),
),
),
);
}
}
And my Settings_View:
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:manebenefitsstudent/services/auth/bloc/auth_bloc.dart';
import 'package:manebenefitsstudent/services/auth/bloc/auth_event.dart';
import 'package:manebenefitsstudent/constants/routes.dart';
import 'package:manebenefitsstudent/services/auth/bloc/auth_state.dart';
import 'package:manebenefitsstudent/utilities/dialogs/logout_dialog.dart';
class SettingsView extends StatefulWidget {
const SettingsView({super.key});
@override
State<SettingsView> createState() => _SettingsViewState();
}
class _SettingsViewState extends State<SettingsView> {
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return BlocListener<AuthBloc, AuthState>(
listener: (context, state) {
if (state is AuthStateLoggedOut) {
Navigator.of(context).pushNamedAndRemoveUntil(
loginViewRoute,
(route) => false,
);
}
},
child: Scaffold(
appBar: AppBar(
title: const Text('Settings'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
ElevatedButton(
onPressed: () {
Navigator.pushNamed(context, categoriesHomeViewRoute);
},
child: const Text('Home'),
),
ElevatedButton(
onPressed: () async {
final shouldLogout = await showLogOutDialog(context);
if (context.mounted && shouldLogout) {
context.read<AuthBloc>().add(const AuthEventLogOut());
}
},
child: const Text('Logout'),
),
ElevatedButton(
onPressed: () {
// Add delete account functionality later
},
child: const Text('Delete Account'),
),
],
),
),
),
);
}
}
I have tried just using
Navigator.of(context).pushNamedAndRemoveUntil
along with the Bloc, but I am not sure if that is what is messing it all up or not.
Again, I am new to flutter so I have little to no idea what I am doing, but it seems there is something going on in my states, after I logout it does put me in the
AuthStateLoggedOut
but its like it does not refresh anything and I can not do anything unless I hot restart. Only then am I able to press the buttons on the login screen and log back in.
Here is a recent log file for the debug console:
Restarted application in 949ms.
I/flutter ( 5226): Event: AuthEventInitialize
I/flutter ( 5226): Event: AuthEventInitialize
W/WindowOnBackDispatcher( 5226): OnBackInvokedCallback is not enabled for the application.
W/WindowOnBackDispatcher( 5226): Set 'android:enableOnBackInvokedCallback="true"' in the application manifest.
I/flutter ( 5226): Event: AuthEventLogOut
D/FirebaseAuth( 5226): Notifying id token listeners about a sign-out event.
D/FirebaseAuth( 5226): Notifying auth state listeners about a sign-out event.
I/flutter ( 5226): Forgot Password Button Pressed
I/flutter ( 5226): Event: AuthEventForgotPassword
I/flutter ( 5226): Register Button Pressed
I/flutter ( 5226): Event: AuthEventShouldRegister
It successfully logged me out and sent me back to the main login view, but I can not do anything from there.