/firebase-tutorials

How to use Firebase auth with Flutter?

Guide to using Firebase Auth with Flutter. Learn setup, Firebase integration for Android/iOS, and how to build a simple registration and login UI.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

How to use Firebase auth with Flutter?

 

Step 1: Set Up a New Flutter Project

 

Before you begin, ensure you have Flutter installed on your machine. If not, visit Flutter’s official documentation for installation instructions. To create a new Flutter project, open your terminal and run:

flutter create firebase_auth_flutter

Navigate into your project directory:

cd firebase_auth_flutter

 

Step 2: Add Firebase to Your Flutter Project

 

First, create a new Firebase project in the Firebase Console. Once your project is created, navigate to the project settings and note your Firebase project ID.

Add the firebase_core and firebase_auth packages to your pubspec.yaml:


dependencies:
  flutter:
    sdk: flutter
  firebase_core: latest_version
  firebase_auth: latest_version

Remember to replace latest_version with the actual latest versions of the libraries.

Run the following command to install these packages:

flutter pub get

 

Step 3: Configure Firebase for Your Platforms

 

Android

  1. In your Firebase project console, click on "Add app" and select Android.
  2. Enter your Android package name (available in your android/app/src/main/AndroidManifest.xml).
  3. Download the google-services.json file from the console and place it in the android/app directory.
  4. Modify your android/build.gradle file to include the Google services classpath:

buildscript {
  dependencies {
    // Add this line
    classpath 'com.google.gms:google-services:4.3.3'
  }
}
  1. Then, in your android/app/build.gradle, add the Google services plugin at the bottom:

apply plugin: 'com.google.gms.google-services'

iOS

  1. In your Firebase project console, click on "Add app" and select iOS.
  2. Enter your iOS bundle ID (you can find this in your ios/Runner.xcodeproj under General → Identity).
  3. Download the GoogleService-Info.plist file and place it in the ios/Runner directory.
  4. Open your ios/Podfile, and ensure the platform is set above 9.0 (if not, adjust it):

platform :ios, '10.0'
  1. Run the following commands to ensure pods are installed:

cd ios
pod install
cd ..

 

Step 4: Initialize Firebase in your Flutter App

 

Initialize Firebase in your Flutter application. Update your main.dart file as follows:


import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("Firebase Auth Demo")),
        body: Center(child: Text("Welcome to Firebase Auth")),
      ),
    );
  }
}

 

Step 5: Implement Firebase Authentication

 

Now, you can start using Firebase Authentication. Create a new Dart file called auth_service.dart to handle authentication logic:


import 'package:firebase_auth/firebase_auth.dart';

class AuthService {
  final FirebaseAuth \_auth = FirebaseAuth.instance;

  Future signInWithEmailAndPassword(String email, String password) async {
    try {
      UserCredential result = await \_auth.signInWithEmailAndPassword(email: email, password: password);
      return result.user;
    } catch (e) {
      print(e.toString());
      return null;
    }
  }

  Future registerWithEmailAndPassword(String email, String password) async {
    try {
      UserCredential result = await \_auth.createUserWithEmailAndPassword(email: email, password: password);
      return result.user;
    } catch (e) {
      print(e.toString());
      return null;
    }
  }

  Future signOut() async {
    try {
      return await \_auth.signOut();
    } catch (e) {
      print(e.toString());
      return null;
    }
  }
}

 

Step 6: Create UI for Authentication

 

Now that you have set up the authentication service, you can create a simple UI to register and login users. Update your main.dart file:


import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'auth\_service.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: AuthenticationScreen(),
    );
  }
}

class AuthenticationScreen extends StatelessWidget {
  final AuthService \_authService = AuthService();
  final TextEditingController \_emailController = TextEditingController();
  final TextEditingController \_passwordController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Firebase Auth Demo")),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TextField(
              controller: \_emailController,
              decoration: InputDecoration(labelText: "Email"),
            ),
            TextField(
              controller: \_passwordController,
              decoration: InputDecoration(labelText: "Password"),
              obscureText: true,
            ),
            SizedBox(height: 20),
            ElevatedButton(
              child: Text("Register"),
              onPressed: () async {
                var result = await \_authService.registerWithEmailAndPassword(
                  \_emailController.text,
                  \_passwordController.text,
                );
                print(result);
              },
            ),
            ElevatedButton(
              child: Text("Login"),
              onPressed: () async {
                var result = await \_authService.signInWithEmailAndPassword(
                  \_emailController.text,
                  \_passwordController.text,
                );
                print(result);
              },
            ),
          ],
        ),
      ),
    );
  }
}

You have successfully initialized Firebase Authentication and created a simple registration and login UI in Flutter. Now you can run your app with the command:

flutter run

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022