Flutter has gained popularity recently with its easy-to-use widgets that are efficient in building applications. Flutter is used alongside Dart for development.
One major component of the development is data handling. Quite often, websites are connected to databases that send and receive data in live applications. One common database used alongside Flutter is Firebase. Both developed by Google, Flutter and Firebase work well together and help reduce coding and improve performance.
To use Flutter with Firebase, you will first need to set dependencies in the pubspec file. You will also have to import firestore
, i.e., the database provided by Firebase for data handling.
dependencies:flutter:sdk: flutter#Adding firebase dependancies to the applicationfirebase_core: "0.7.0"cloud_firestore: ^2.5.3
Once you add firestore
, run the following to update your files:
flutter pub get
Now, import the Firebase dependencies into your Dart file.
import 'package:flutter/material.dart';// Import the firebase_core pluginimport 'package:firebase_core/firebase_core.dart';//Import firestore databaseimport 'package:cloud_firestore/cloud_firestore.dart';
The application is ready to use Firebase. You can now continue to initialize the application by importing the config file after you set it up on the Firebase console.
Once this file is added to your project directory, you can connect to the database by initializing it within the application.
void main() async {//Initializing Database when starting the application.WidgetsFlutterBinding.ensureInitialized();await Firebase.initializeApp();runApp(App());}
Data reading is simple when you can retrieve the snapshots and parse them according to your needs.
The code below shows how a widget can be used to read data and display it onto the application.
class GetStudentName extends StatelessWidget {final String documentId;GetStudentName(this.documentId);@overrideWidget build(BuildContext context) {CollectionReference student = FirebaseFirestore.instance.collection('students');return FutureBuilder<DocumentSnapshot>(//Fetching data from the documentId specified of the studentfuture: students.doc(documentId).get(),builder:(BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {//Error Handling conditionsif (snapshot.hasError) {return Text("Something went wrong");}if (snapshot.hasData && !snapshot.data!.exists) {return Text("Document does not exist");}//Data is output to the userif (snapshot.connectionState == ConnectionState.done) {Map<String, dynamic> data = snapshot.data!.data() as Map<String, dynamic>;return Text("Full Name: ${data['full_name']} ${data['last_name']}");}return Text("loading");},);}}
Similarly, to add/edit a simple document to Firebase, i.e., writing data, you can refer to the collection inside the application and call the function as shown below.
CollectionReference students = FirebaseFirestore.instance.collection('students');Future<void> addStudent() {// Calling the collection to add a new userreturn students//adding to firebase collection.add({//Data added in the form of a dictionary into the document.'full_name': fullName,'grade': grade,'age': age}).then((value) => print("Student data Added")).catchError((error) => print("Student couldn't be added."));}//For setting a specific document ID use .set instead of .addusers.doc(documentId).set({//Data added in the form of a dictionary into the document.'full_name': fullName,'grade': grade,'age': age});//For updating docs, you can use this function.Future<void> updateUser() {return students//referring to document ID, this can be queried or named when added accordingly.doc(documentId)//updating grade value of a specific student.update({'grade': newGrade}).then((value) => print("Student data Updated")).catchError((error) => print("Failed to update data"));}