Learn iOS Programming  

Connect a Flutter App to Firebase for User Authentication

🚀 Introduction

User authentication is one of the most common features in mobile apps. Whether you’re building a chat app, an e-commerce store, or a social platform, you’ll often need users to sign up, log in, and manage their accounts securely.

Flutter, Google’s cross-platform UI toolkit, makes it easy to build mobile apps, while Firebase Authentication provides a backend service to handle user sign-up, login, and identity management. By connecting Flutter with Firebase, you can implement authentication methods like email/password, Google sign-in, or social login with minimal backend code.

📦 Step 1. Set Up Firebase Project

  1. Go to the Firebase Console.

  2. Click Add Project and enter your project name.

  3. Disable Google Analytics if not needed.

  4. Once the project is created, you’ll be redirected to the Firebase dashboard.

👉 This Firebase project will act as the backend for your Flutter app.

📱 Step 2. Add Your Flutter App to Firebase

  1. In the Firebase console, click on Add App → choose iOS or Android.

  2. For Android

    • Provide your app’s package name (found in android/app/build.gradle).

    • Download the google-services.json file.

    • Place it in android/app/.

  3. For iOS

    • Provide your app’s bundle ID (found in ios/Runner.xcodeproj).

    • Download the GoogleService-Info.plist file.

    • Add it to ios/Runner/ using Xcode.

⚙️ Step 3. Configure Firebase SDK in Flutter

Open your pubspec.yaml and add Firebase dependencies:

dependencies:
  flutter:
    sdk: flutter
  firebase_core: ^2.0.0
  firebase_auth: ^4.0.0

Then run:

flutter pub get

Initialize Firebase in your app by editing main.dart:

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(
        body: Center(child: Text('Firebase Initialized!')),
      ),
    );
  }
}

👤 Step 4. Enable Authentication Methods in Firebase

  1. Go to Firebase Console → Authentication → Sign-in method.

  2. Enable the authentication methods you want:

    • Email/Password

    • Google

    • Facebook

    • Apple

    • Phone number

For this example, let’s use Email/Password authentication.

🔑 Step 5. Implement Email/Password Authentication

Sign-Up (Create User)

import 'package:firebase_auth/firebase_auth.dart';

Future<void> registerUser(String email, String password) async {
  try {
    UserCredential userCredential = await FirebaseAuth.instance
        .createUserWithEmailAndPassword(email: email, password: password);
    print("User registered: ${userCredential.user?.uid}");
  } catch (e) {
    print("Error: $e");
  }
}

Login (Sign-In User)

Future<void> loginUser(String email, String password) async {
  try {
    UserCredential userCredential = await FirebaseAuth.instance
        .signInWithEmailAndPassword(email: email, password: password);
    print("User logged in: ${userCredential.user?.uid}");
  } catch (e) {
    print("Error: $e");
  }
}

Logout (Sign-Out User)

Future<void> logoutUser() async {
  await FirebaseAuth.instance.signOut();
  print("User logged out");
}

🎯 Flutter Skill Challenge — Test What You Learned and Win Rewards!

Now that you’ve learned how to connect Flutter with Firebase Authentication, it’s time to test your skills! 🎉

👉 Take the Flutter Skill Challenge to apply what you’ve learned. You’ll earn Sharp Tokens 🏆 as a reward for your knowledge!

👉 Don’t just read—apply your skills and get rewarded today!

📡 Step 6. Listen to Authentication State

Firebase lets you listen to whether a user is signed in or signed out:

StreamBuilder<User?> (
  stream: FirebaseAuth.instance.authStateChanges(),
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.active) {
      if (snapshot.hasData) {
        return HomePage(); // User logged in
      } else {
        return LoginPage(); // User logged out
      }
    }
    return CircularProgressIndicator();
  },
)

⚠️ Common Pitfalls

  • Forgetting to place google-services.json or GoogleService-Info.plist correctly.

  • Not calling Firebase.initializeApp() before using Firebase services.

  • Using old versions of dependencies (always check the latest versions).

  • Forgetting to enable the sign-in method in the Firebase Console.

📝 Best Practices

  • Always validate email and password before sending them to Firebase.

  • Use try-catch for error handling (e.g., weak passwords, invalid email).

  • Secure API keys (though Firebase keys are safe to be public, restrict them via Firebase settings).

  • Consider using Firebase UI packages for ready-made authentication UIs.

🎯 Conclusion

Connecting a Flutter app to Firebase for authentication is straightforward once you understand the steps:

  1. Create a Firebase project

  2. Add your app to Firebase

  3. Configure SDK

  4. Enable the authentication method

  5. Implement login, signup, and logout

  6. Listen to the auth state

By combining Flutter’s UI flexibility with Firebase’s secure backend, you can build apps with seamless user authentication — from email/password to Google sign-in and beyond.