Firebase for Flutter: Adding Authentication

Gene Rodriguez
4 min readJul 3, 2023

--

In this article you’ll be able to integrate Firebase Auth in Flutter app.

In the previous article, we discussed how to create a Flutter app and configure and integrate Firebase.

Video Source: Firebase official Youtube channel

Authentication is one of the building blocks of an app so that you can store any data of each users through their unique id.

In Firebase, you can use different sign-in providers like email and password, Google sign-in and other social media auth providers.

For our newly created app in the previous article, we’ll be using email and password.

Setup

Below is the guide on how to enable Firebase Auth in the console.

Head to your project dashboard in Firebase console and click Authentication under the Build section.

Click the Authentication service.
Click “Get Started”.
Choose “Email / Password” in Sign-in providers.
Enable the switch in Email/Password and click Save.
Email/Password successfully enabled.

Now, let’s add some code to our app to be able to bind this service.

First, let’s create our login page and add this block of codes.

login.dart

  FirebaseAuth auth = FirebaseAuth.instance;  

final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();

final _formKey = GlobalKey<FormState>();

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Login"),
),
body: Form(
key: _formKey,
child: Container(
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.start,
children: [
TextFormField(
controller: _emailController,
decoration: const InputDecoration(
hintText: "Email",
icon: Icon(Icons.email_outlined),
),
),
const SizedBox(
height: 10,
),
TextField(
controller: _passwordController,
decoration: const InputDecoration(
hintText: "Password",
icon: Icon(Icons.password_outlined),
),
),
const SizedBox(
height: 50,
),
ElevatedButton.icon(
onPressed: () {},
label: const Text(
"Sign In",
),
icon: const Icon(Icons.login_outlined),
),
const SizedBox(
height: 10,
),
OutlinedButton.icon(
onPressed: () {},
icon: const Icon(Icons.add_circle_outline_outlined),
label: const Text("Sign Up"),
),
],
),
),
),
);
}

main.dart

class MyApp extends StatelessWidget {
const MyApp({super.key});

// This widget is the root of your application.
@override
Widget build(BuildContext context) {
FirebaseAuth auth= FirebaseAuth.instance;

return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: auth.currentUser == null
? const LoginPage()
: const MyHomePage(title: 'Home'),
);
}
}

As a result, this will be our Login page.

And now, let’s bind our widget to our Firebase Auth service.

Add this methods below of the build.

void signIn() {
if (_formKey.currentState!.validate()) {
auth
.signInWithEmailAndPassword(
email: _emailController.text, password: _passwordController.text)
.whenComplete(
() => ScaffoldMessenger.of(context)
.showSnackBar(
const SnackBar(
content: Text("Logged In Successfully"),
),
)
.closed
.whenComplete(
() => Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => const MyHomePage(title: "Home"),
),
),
),
);
}
}
void signUp() {
if (_formKey.currentState!.validate()) {
auth
.createUserWithEmailAndPassword(
email: _emailController.text, password: _passwordController.text)
.whenComplete(
() => ScaffoldMessenger.of(context)
.showSnackBar(
const SnackBar(
content: Text("Successfully Signed Up"),
),
)
.closed
.whenComplete(
() => Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => const MyHomePage(title: "Home"),
),
),
),
);
}
}

Time to setup AppCheck service.

Go to AppCheck under Build section in Firebase.

Click “Register”.

To get the SHA-256, open the android project and run the Gradle command.

Right click the android project.
Click “Open Android Module in Android Studio”.
Click the Terminal icon.
Run this command to get the SHA-256.

Copy the SHA-256 from debug config section and paste it to the AppCheck in Firebase Console.

Paste the SHA-256 and check the terms and condition then click ‘Save’.

Add this to your pubspec.yaml.

firebase_app_check:

Now, add the FirebaseAppCheck and the main method looks like this.

main.dart

void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);

FirebaseAppCheck firebaseAppCheck = FirebaseAppCheck.instance;
firebaseAppCheck.activate(
androidProvider: AndroidProvider.debug,
);
firebaseAppCheck.getToken().then((value) => print("APP CHECK: $value"));
runApp(const MyApp());
}

If this pops up in the logs, enter the debug key in Firebase AppCheck console.

Enter this debug secret into the allow list in the Firebase Console
for your project: DEBUG_SECRET
Click the ‘Menu’, then click ‘Manage Debug Tokens’.
Add the generated debug token and click ‘Done’.

Congrats, we’re done setting up the Firebase Auth.

Thank you for reading!

--

--