Flutter Firebase Database Examples
Flutter firebase database Examples.
Introduction
Firebase is a mobile and web application development platform developed by Firebase Inc. It provides various services like real-time database, authentication, cloud storage, and more. Flutter is an open-source UI software development kit created by Google for building natively compiled applications for mobile, web, and desktop from a single codebase. In this tutorial, we will explore how to use the firebase_database
package in Flutter to interact with the Firebase Realtime Database.
Installation
To get started, you need to add the firebase_database
dependency to your Flutter project. Open the pubspec.yaml
file and add the following line under the dependencies
section:
dependencies:
flutter:
sdk: flutter
firebase_database: ^7.1.1
Save the file and run the following command in the terminal to fetch the package:
flutter pub get
Example 1: Read Data from Firebase Realtime Database
In this example, we will retrieve data from the Firebase Realtime Database using the firebase_database
package.
Import the necessary packages:
import 'package:firebase_database/firebase_database.dart';
Create an instance of the
FirebaseDatabase
class:final database = FirebaseDatabase.instance;
Retrieve the data from the database:
database.reference().child('users').once().then((DataSnapshot snapshot) {
Map<dynamic, dynamic> data = snapshot.value;
print(data);
});The
once()
method retrieves the data from the specified location in the database. The returnedDataSnapshot
object contains the retrieved data.Run the code and check the console for the output.
Expected Output: The retrieved data will be printed on the console.
Example 2: Write Data to Firebase Realtime Database
In this example, we will write data to the Firebase Realtime Database using the firebase_database
package.
Import the necessary packages:
import 'package:firebase_database/firebase_database.dart';
Create an instance of the
FirebaseDatabase
class:final database = FirebaseDatabase.instance;
Write data to the database:
database.reference().child('users').child('1').set({
'name': 'John Doe',
'email': '[email protected]',
});The
set()
method sets the data at the specified location in the database.Run the code to write the data to the database.
Example 3: Update Data in Firebase Realtime Database
In this example, we will update data in the Firebase Realtime Database using the firebase_database
package.
Import the necessary packages:
import 'package:firebase_database/firebase_database.dart';
Create an instance of the
FirebaseDatabase
class:final database = FirebaseDatabase.instance;
Update data in the database:
database.reference().child('users').child('1').update({
'name': 'Jane Doe',
});The
update()
method updates the specified fields in the database.Run the code to update the data in the database.
Example 4: Delete Data from Firebase Realtime Database
In this example, we will delete data from the Firebase Realtime Database using the firebase_database
package.
Import the necessary packages:
import 'package:firebase_database/firebase_database.dart';
Create an instance of the
FirebaseDatabase
class:final database = FirebaseDatabase.instance;
Delete data from the database:
database.reference().child('users').child('1').remove();
The
remove()
method deletes the data at the specified location in the database.Run the code to delete the data from the database.
Example 5: Listen to Realtime Updates from Firebase Realtime Database
In this example, we will listen to realtime updates from the Firebase Realtime Database using the firebase_database
package.
Import the necessary packages:
import 'package:firebase_database/firebase_database.dart';
Create an instance of the
FirebaseDatabase
class:final database = FirebaseDatabase.instance;
Listen to changes in the database:
database.reference().child('users').onChildAdded.listen((event) {
print('New user added: ${event.snapshot.key}');
print('Data: ${event.snapshot.value}');
});The
onChildAdded
method listens for new child nodes added to the specified location in the database.Run the code and observe the console for updates.
Expected Output: Whenever a new user is added to the
users
node in the database, the key and value of the new user will be printed on the console.
Example 6: Query Data from Firebase Realtime Database
In this example, we will query data from the Firebase Realtime Database using the firebase_database
package.
Import the necessary packages:
import 'package:firebase_database/firebase_database.dart';
Create an instance of the
FirebaseDatabase
class:final database = FirebaseDatabase.instance;
Query data from the database:
database
.reference()
.child('users')
.orderByChild('age')
.equalTo(25)
.once()
.then((DataSnapshot snapshot) {
Map<dynamic, dynamic> data = snapshot.value;
print(data);
});The
orderByChild()
method sorts the data based on the specified child field, and theequalTo()
method filters the data based on the specified value.Run the code and check the console for the output.
Expected Output: The queried data will be printed on the console.
Example 7: Pagination in Firebase Realtime Database
In this example, we will implement pagination in the Firebase Realtime Database using the firebase_database
package.
Import the necessary packages:
import 'package:firebase_database/firebase_database.dart';
Create an instance of the
FirebaseDatabase
class:final database = FirebaseDatabase.instance;
Implement pagination:
int pageSize = 10;
int currentPage = 1;
database
.reference()
.child('users')
.orderByKey()
.startAt('$currentPage')
.limitToFirst(pageSize)
.once()
.then((DataSnapshot snapshot) {
Map<dynamic, dynamic> data = snapshot.value;
print(data);
});The
startAt()
method specifies the starting point for the query, and thelimitToFirst()
method limits the number of results to be retrieved.Run the code and check the console for the output.
Expected Output: The paginated data will be printed on the console.
Example 8: Working with Nested Data in Firebase Realtime Database
In this example, we will work with nested data in the Firebase Realtime Database using the firebase_database
package.
Import the necessary packages:
import 'package:firebase_database/firebase_database.dart';
Create an instance of the
FirebaseDatabase
class:final database = FirebaseDatabase.instance;
Write nested data to the database:
database.reference().child('users').child('1').set({
'name': 'John Doe',
'email': '[email protected]',
'address': {
'street': '123 Main St',
'city': 'New York',
'state': 'NY',
},
});The nested data is represented as a nested map.
Run the code to write the nested data to the database.
Example 9: Working with Lists in Firebase Realtime Database
In this example, we will work with lists in the Firebase Realtime Database using the firebase_database
package.
Import the necessary packages:
import 'package:firebase_database/firebase_database.dart';
Create an instance of the
FirebaseDatabase
class:final database = FirebaseDatabase.instance;
Write a list to the database:
database.reference().child('users').child('1').child('friends').set([
'Alice',
'Bob',
'Charlie',
]);The list data is represented as a list of values.
Run the code to write the list to the database.
Example 10: Working with Transactions in Firebase Realtime Database
In this example, we will work with transactions in the Firebase Realtime Database using the firebase_database
package.
Import the necessary packages:
import 'package:firebase_database/firebase_database.dart';
Create an instance of the
FirebaseDatabase
class:final database = FirebaseDatabase.instance;
Perform a transaction:
database.reference().child('users').child('1').runTransaction((mutableData) {
if (mutableData.value == null) {
return mutableData;
}
mutableData.value['age'] = 30;
return mutableData;
});The
runTransaction()
method allows you to perform atomic updates on data in the database.Run the code to perform the transaction.
Note: Don't forget to configure your Flutter project with Firebase by following the official Firebase setup instructions.