Flutter Firebase Integration: How to Build Real-time Apps

Are you ready to take your Flutter app to the next level? Do you want to build real-time apps that can handle user interactions and data updates in real-time? If so, then you need to integrate Firebase into your Flutter app.

Firebase is a powerful backend platform that provides a wide range of features and services for building real-time apps. With Firebase, you can easily store and sync data, authenticate users, and send notifications to your users.

In this article, we will show you how to integrate Firebase into your Flutter app and build real-time apps that can handle user interactions and data updates in real-time.

Prerequisites

Before we get started, you need to have the following:

Step 1: Create a new Flutter project

The first step is to create a new Flutter project. Open your terminal or command prompt and run the following command:

flutter create myapp

This will create a new Flutter project named myapp. Once the project is created, navigate to the project directory by running the following command:

cd myapp

Step 2: Add Firebase to your Flutter project

The next step is to add Firebase to your Flutter project. To do this, you need to follow these steps:

Step 2.1: Create a Firebase project

Go to the Firebase Console and create a new project. Once the project is created, click on the "Add Firebase to your web app" button to get the Firebase configuration details.

Step 2.2: Add the Firebase configuration details to your Flutter project

Open the pubspec.yaml file in your Flutter project and add the following dependencies:

dependencies:
  firebase_core: ^1.0.0
  firebase_auth: ^1.0.0
  cloud_firestore: ^1.0.0

Next, open the android/app/build.gradle file and add the following lines of code inside the dependencies block:

implementation 'com.google.firebase:firebase-core:17.0.0'
implementation 'com.google.firebase:firebase-auth:19.0.0'
implementation 'com.google.firebase:firebase-firestore:21.0.0'

Next, open the ios/Podfile file and add the following lines of code:

pod 'Firebase/Core'
pod 'Firebase/Auth'
pod 'Firebase/Firestore'

Save the changes and run the following command to install the dependencies:

flutter pub get

Step 2.3: Initialize Firebase in your Flutter app

Open the main.dart file in your Flutter project and add the following lines of code:

import 'package:firebase_core/firebase_core.dart';

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

This code initializes Firebase in your Flutter app.

Step 3: Authenticate users with Firebase

The next step is to authenticate users with Firebase. Firebase provides several authentication methods, including email and password, Google, Facebook, Twitter, and more.

In this article, we will show you how to authenticate users with email and password.

Step 3.1: Create a login screen

Create a new file named login_screen.dart in your Flutter project and add the following code:

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

class LoginScreen extends StatefulWidget {
  @override
  _LoginScreenState createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  final _formKey = GlobalKey<FormState>();
  final _emailController = TextEditingController();
  final _passwordController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Login'),
      ),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              TextFormField(
                controller: _emailController,
                decoration: InputDecoration(labelText: 'Email'),
                validator: (value) {
                  if (value.isEmpty) {
                    return 'Please enter your email';
                  }
                  return null;
                },
              ),
              TextFormField(
                controller: _passwordController,
                decoration: InputDecoration(labelText: 'Password'),
                obscureText: true,
                validator: (value) {
                  if (value.isEmpty) {
                    return 'Please enter your password';
                  }
                  return null;
                },
              ),
              SizedBox(height: 16.0),
              Center(
                child: RaisedButton(
                  onPressed: () async {
                    if (_formKey.currentState.validate()) {
                      try {
                        await FirebaseAuth.instance.signInWithEmailAndPassword(
                          email: _emailController.text.trim(),
                          password: _passwordController.text.trim(),
                        );
                        Navigator.of(context).pushReplacementNamed('/home');
                      } on FirebaseAuthException catch (e) {
                        if (e.code == 'user-not-found') {
                          print('No user found for that email.');
                        } else if (e.code == 'wrong-password') {
                          print('Wrong password provided for that user.');
                        }
                      }
                    }
                  },
                  child: Text('Login'),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

This code creates a login screen with email and password fields. It also validates the form and authenticates the user with Firebase when the login button is pressed.

Step 3.2: Create a registration screen

Create a new file named registration_screen.dart in your Flutter project and add the following code:

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

class RegistrationScreen extends StatefulWidget {
  @override
  _RegistrationScreenState createState() => _RegistrationScreenState();
}

class _RegistrationScreenState extends State<RegistrationScreen> {
  final _formKey = GlobalKey<FormState>();
  final _emailController = TextEditingController();
  final _passwordController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Registration'),
      ),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              TextFormField(
                controller: _emailController,
                decoration: InputDecoration(labelText: 'Email'),
                validator: (value) {
                  if (value.isEmpty) {
                    return 'Please enter your email';
                  }
                  return null;
                },
              ),
              TextFormField(
                controller: _passwordController,
                decoration: InputDecoration(labelText: 'Password'),
                obscureText: true,
                validator: (value) {
                  if (value.isEmpty) {
                    return 'Please enter your password';
                  }
                  return null;
                },
              ),
              SizedBox(height: 16.0),
              Center(
                child: RaisedButton(
                  onPressed: () async {
                    if (_formKey.currentState.validate()) {
                      try {
                        await FirebaseAuth.instance.createUserWithEmailAndPassword(
                          email: _emailController.text.trim(),
                          password: _passwordController.text.trim(),
                        );
                        Navigator.of(context).pushReplacementNamed('/home');
                      } on FirebaseAuthException catch (e) {
                        if (e.code == 'weak-password') {
                          print('The password provided is too weak.');
                        } else if (e.code == 'email-already-in-use') {
                          print('The account already exists for that email.');
                        }
                      } catch (e) {
                        print(e);
                      }
                    }
                  },
                  child: Text('Register'),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

This code creates a registration screen with email and password fields. It also validates the form and creates a new user with Firebase when the register button is pressed.

Step 3.3: Create a home screen

Create a new file named home_screen.dart in your Flutter project and add the following code:

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

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Home'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('You are logged in!'),
            SizedBox(height: 16.0),
            RaisedButton(
              onPressed: () async {
                await FirebaseAuth.instance.signOut();
                Navigator.of(context).pushReplacementNamed('/login');
              },
              child: Text('Logout'),
            ),
          ],
        ),
      ),
    );
  }
}

This code creates a home screen with a logout button. It also logs out the user from Firebase when the logout button is pressed.

Step 3.4: Add navigation to your Flutter app

Open the main.dart file in your Flutter project and add the following code:

import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:myapp/screens/home_screen.dart';
import 'package:myapp/screens/login_screen.dart';
import 'package:myapp/screens/registration_screen.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Firebase Integration',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      initialRoute: FirebaseAuth.instance.currentUser == null ? '/login' : '/home',
      routes: {
        '/login': (context) => LoginScreen(),
        '/registration': (context) => RegistrationScreen(),
        '/home': (context) => HomeScreen(),
      },
    );
  }
}

This code adds navigation to your Flutter app. It also checks if the user is logged in or not and redirects the user to the login screen or home screen accordingly.

Step 4: Store and sync data with Firebase

The final step is to store and sync data with Firebase. Firebase provides a real-time database and a cloud firestore database for storing and syncing data.

In this article, we will show you how to store and sync data with the cloud firestore database.

Step 4.1: Create a new collection in Firestore

Go to the Firebase Console and create a new collection in the cloud firestore database. Once the collection is created, add a new document with the following fields:

Step 4.2: Create a profile screen

Create a new file named profile_screen.dart in your Flutter project and add the following code:

import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class ProfileScreen extends StatefulWidget {
  @override
  _ProfileScreenState createState() => _ProfileScreenState();
}

class _ProfileScreenState extends State<ProfileScreen> {
  final _formKey = GlobalKey<FormState>();
  final _nameController = TextEditingController();
  final _emailController = TextEditingController();

  @override
  void initState() {
    super.initState();
    FirebaseFirestore.instance
        .collection('users')
        .doc(FirebaseAuth.instance.currentUser.uid)
        .get()
        .then((value) {
      _nameController.text = value.data()['name'];
      _emailController.text = value.data()['email'];
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Profile'),
      ),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              TextFormField(
                controller: _nameController,
                decoration: InputDecoration(labelText: 'Name'),
                validator: (value) {
                  if (value.isEmpty) {
                    return 'Please enter your name';
                  }
                  return null;
                },
              ),
              TextFormField(
                controller: _emailController,
                decoration: InputDecoration(labelText: 'Email'),
                validator: (value) {
                  if (value.isEmpty) {
                    return 'Please enter your email';
                  }
                  return null;
                },
              ),
              SizedBox(height: 16.0),
              Center(
                child: RaisedButton(
                  onPressed: () async {
                    if (_formKey.currentState.validate()) {
                      await FirebaseFirestore.instance
                          .collection('users')
                          .doc(FirebaseAuth.instance.currentUser.uid)
                          .set({
                        'name': _nameController.text.trim(),
                        'email': _emailController.text.trim(),
                      });
                      Navigator.of(context).pop();
                    }
                  },
                  child: Text('Save'),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

This code creates a profile screen with name and email fields. It also retrieves the user's data from Firestore and updates the data when the save button is pressed.

Step 4.3: Add navigation to your Flutter app

Open the main.dart file in your Flutter project and add the following code:

import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:myapp/screens/home_screen.dart';
import 'package:myapp/screens/login_screen.dart';
import 'package:myapp/screens/registration_screen.dart';
import 'package:myapp/screens/profile_screen.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Firebase Integration',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      initialRoute: FirebaseAuth.instance.currentUser == null ? '/login' : '/home',
      routes: {
        '/login': (context) => LoginScreen(),
        '/registration': (context) => RegistrationScreen(),
        '/home': (context) => HomeScreen(),
        '/profile': (context) => ProfileScreen(),
      },
    );
  }
}

This code adds navigation to your Flutter app. It also adds a new route for the profile screen.

Step 4.4: Add a button to the home screen

Open the home_screen.dart file in your Flutter project and add the following code:

import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:myapp/screens/profile_screen.dart';

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Home'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('You are logged in!'),
            SizedBox(height: 16.0),
            RaisedButton(
              onPressed: () {
                Navigator.of(context).pushNamed('/profile');
              },
              child: Text('Edit Profile'),
            ),
            SizedBox(height: 16.0),
            RaisedButton(
              onPressed: () async {
                await FirebaseAuth.instance.signOut();
                Navigator.of(context).pushReplacementNamed('/login');
              },
              child: Text('Logout'),
            ),
          ],
        ),
      ),
    );
  }
}

This code adds a new button to the home screen that navigates to the profile screen when pressed.

Conclusion

Congratulations! You have successfully integrated Firebase into your Flutter app and built real-time apps that can handle user interactions and data updates in real-time.

In this article, we have shown you how to authenticate users with Firebase, store and sync data with the cloud firestore database, and navigate between screens in your Flutter app.

We hope this article has been helpful to you. If you have any questions or feedback, please feel free to leave a comment below. Happy coding!

Editor Recommended Sites

AI and Tech News
Best Online AI Courses
Classic Writing Analysis
Tears of the Kingdom Roleplay
Rust Software: Applications written in Rust directory
Learn Python: Learn the python programming language, course by an Ex-Google engineer
AI Art - Generative Digital Art & Static and Latent Diffusion Pictures: AI created digital art. View AI art & Learn about running local diffusion models, transformer model images
Visual Novels: AI generated visual novels with LLMs for the text and latent generative models for the images
Developer Cheatsheets - Software Engineer Cheat sheet & Programming Cheatsheet: Developer Cheat sheets to learn any language, framework or cloud service