Flutter and Firebase Integration: Real-time Database and Authentication

Flutter and Firebase Integration: Real-time Database and Authentication

In the realm of modern mobile app development, the synchronization of real-time data across devices is pivotal for delivering engaging and dynamic user experiences. Firebase Realtime Database, a NoSQL cloud-based solution, offers an elegant answer to this need. In this blog, we will delve into the integration of Firebase Realtime Database into a Flutter application, focusing on CRUD (Create, Read, Update, Delete) operations. Detailed code examples will guide you through the process of incorporating Firebase Realtime Database functionalities into your Flutter projects.

Prerequisites

Before embarking on the implementation journey, ensure the following prerequisites are set up:

  1. Flutter SDK is installed on your machine.

  2. A Firebase project was created in the Firebase console Firebase Console.

  3. FlutterFire plugin dependencies added to your Flutter project FlutterFire Documentation.

Step 1: Setting up the Firebase Project

  1. Create a new Flutter project using the Flutter command-line tool or your preferred IDE.

  2. Navigate to the Firebase console and create a new project.

  3. Click on "Add Firebase to your Flutter app" and follow the setup instructions, which will provide a google-services.json file. Place this file in your Flutter project's Android/app directory.

Step 2: Adding Firebase Dependencies

Open your Flutter project and navigate to the pubspec.yaml file. Add the following dependencies under the dependencies section:

dependencies:

flutter:

sdk: flutter

firebase_core: ^1.4.0

firebase_database: ^11.0.0

Run flutter pub to fetch the newly added dependencies.

Step 3: Initializing Firebase Realtime Database

Open the main.dart file in your Flutter project. Import the necessary Firebase and Flutter packages:

import 'package:flutter/material.dart';

import 'package:firebase_core/firebase_core.dart';

import 'package:firebase_database/firebase_database.dart';

Initialize Firebase in the main() function:

void main() async {

WidgetsFlutterBinding.ensureInitialized();

await Firebase.initializeApp();

runApp(MyApp());

}

CRUD Operations with Firebase Realtime Database

Now, let’s dive into the code examples for performing CRUD operations using Firebase Realtime Database.

Create Operation:

To create a new record in the database, use the push() method to generate a unique key and then set the desired values using the set() method.

void createRecord() {

DatabaseReference databaseReference =

FirebaseDatabase.instance.reference().child('users');

databaseReference.push().set({

'name': 'Alyssa Pham',

'email': 'alyssapham@example.com',

'age': 35,

});

}

Read Operation:

To retrieve data from the database, use the onValue event listener to receive real-time updates and access the snapshot's DataSnapshot object to extract the data.

void readData() {

DatabaseReference databaseReference =

FirebaseDatabase.instance.reference().child('users');

databaseReference.onValue.listen((event) {

DataSnapshot dataSnapshot = event.snapshot;

Map<dynamic, dynamic> values = dataSnapshot.value;

values.forEach((key, values) {

print('Key: $key');

print('Name: ${values['name']}');

print('Email: ${values['email']}');

print('Age: ${values['age']}');

});

});

}

Update Operation:

To update an existing record, reference the specific record using its unique key and then call the update() method to modify the desired fields.

void updateData() {

DatabaseReference databaseReference =

FirebaseDatabase.instance.reference().child('users');

String recordKey = '-Mfa7Gfrd2Er6q9k7Jbv'; // Replace with your record key

databaseReference.child(recordKey).update({

'name': 'Jane Doe',

'age': 25,

});

}

Delete Operation:

To remove a record from the database, reference the specific record using its unique key and call the remove() method.

void deleteData() {

DatabaseReference databaseReference =

FirebaseDatabase.instance.reference().child('users');

String recordKey = '-Mfa7Gfrd2Er6q9k7Jbv'; // Replace with your record key

databaseReference.child(recordKey).remove();

}

Interested in any Flutter app development services? We're here to assist!