Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
15 views12 pages

MadExp6 (A)

The document outlines a laboratory experiment focused on integrating Firebase with a Flutter application for data management. It details the steps for setting up a Firebase project, adding Android support, and implementing Firebase features in the Flutter app, including reading and writing data. The experiment concludes with a successful demonstration of a production-ready app that utilizes Firebase services.

Uploaded by

Vishaka Irabatti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views12 pages

MadExp6 (A)

The document outlines a laboratory experiment focused on integrating Firebase with a Flutter application for data management. It details the steps for setting up a Firebase project, adding Android support, and implementing Firebase features in the Flutter app, including reading and writing data. The experiment concludes with a successful demonstration of a production-ready app that utilizes Firebase services.

Uploaded by

Vishaka Irabatti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

DEPARTMENT OF INFORMATION TECHNOLOGY

EXPERIMENT NO. 06 Batch/Roll No.: T2/621

Aim: To write and read data into/from Firebase


Lab Outcome 03
To analyze and Build production ready Flutter App by incorporating backend
services and deploying on Android / iOS

Compiler / Tool : Flutter sdk, Android studio, Google firebase

Theory:
Firebase is a Backend-as-a-Service (BaaS) app development platform that provides hosted
backend services such as a realtime database, cloud storage, authentication, crash reporting,
machine learning, remote configuration, and hosting for your static files.
Installation and Configuration:

Creating a New Firebase Project:


First, log in with your Google account to manage your Firebase projects. From within the
Firebase dashboard, select the Create new project button and give it a name:

Next, we’re given the option to enable Google Analytics.

1
DEPARTMENT OF INFORMATION TECHNOLOGY

If you choose to use Google Analytics, you will need to review and accept the terms and
conditions prior to project creation.
After pressing Continue, your project will be created and resources will be provisioned. You
will then be directed to the dashboard for the new project.
Adding Android support:
Registering the App In order to add Android support to our Flutter application, select the Android
logo from the dashboard. This brings us to the following screen:

2
DEPARTMENT OF INFORMATION TECHNOLOGY

The most important thing here is to match up the Android package name that you choose here
with the one inside of our application.The structure consists of at least two segments. A common
pattern is to use a domain name, a company name, and the application name:
com.example.flutterfirebaseexample
Once you’ve decided on a name, open android/app/build.gradle in your code editor and
update the applicationId to match the Android package name:
android/app/build.gradle
...
defaultConfig {
// TODO: Specify your own unique Application ID
(https://developer.android.com/studio/build/application-id.html).
applicationId 'com.example.flutterfirebaseexample'
...
}
...
You can skip the app nickname and debug signing keys at this stage. Select Register app to
continue.
Downloading the Config File
The next step is to add the Firebase configuration file into our Flutter project. This is important
as it contains the API keys and other critical information for Firebase to use.
Select Download google-services.json from this page:

Next, move the google-services.json file to the android/app directory within the Flutter
project.
Adding the Firebase SDK
We’ll now need to update our Gradle configuration to include the Google Services plugin. Open
android/build.gradle in your code editor and modify it to include the following:

3
DEPARTMENT OF INFORMATION TECHNOLOGY

android/buiild.gradle /buildscript
{
repositories {
// Check that you have the following line (if not, add it):
google() // Google's Maven repository
}
dependencies {
...
// Add this line
classpath 'com.google.gms:google-services:4.3.6'
}
}

allprojects {
...
repositories {
// Check that you have the following line (if not, add it):
google() // Google's Maven repository
...
}
}
Finally, update the app level file at android/app/build.gradle to include the following:
android/app/build.gradle
apply plugin: 'com.android.application'
// Add this line
apply plugin: 'com.google.gms.google-services'

dependencies {
// Import the Firebase BoM
implementation platform('com.google.firebase:firebase-bom:28.0.0')

// Add the dependencies for any other desired Firebase products


// https://firebase.google.com/docs/android/setup#available-libraries
}
With this update, we’re essentially applying the Google Services plugin as well as looking at
how other Flutter Firebase plugins can be activated such as Analytics.
From here, run your application on an Android device or simulator. If everything has worked
correctly, you should get the following message in the dashboard:

4
DEPARTMENT OF INFORMATION TECHNOLOGY

Implementation:
We need to follow the 3-step procedure:

1. Adding firebase to our app


2. Firebase Setup
3. Implement using Code

Adding firebase to our app


To interact with firebase we have to register our app to firebase.
Firebase Setup
After completing the above setup follow these steps:
Step 1: After creating your project on the left-hand side you will see these options

Step2: Select the cloud Firestore and then select create database and then select test mode and
press next.

5
Step 3: Select any location or you can keep it as it is and press enable

After creating Cloud Firestore you will see the empty database, now you have to just create a
table and add data to it later we will add data from our app. Follow the below steps to create a
collection(tables).
Step 1: Press Start collection

6
[Document title]
Step 2: Enter a name for collection id and select auto id for its document

7
DEPARTMENT OF INFORMATION TECHNOLOGY

Step 3: Press Add Field and add Field and Value as key-value pair

Step 4: Finally this is how your final screen will look

Step 1: In your flutter project open pubspec.yaml and under dependencies add the following
packages:
dependencies:
flutter:
sdk: flutter
firebase_core: "^0.5.0"
cloud_firestore: ^0.14.1
Save the above file.
Note: While adding the above code ensure that the code added should on the same level as
flutter.
Step 2: In the terminal execute the following line.
flutter pub get
Before executing the above lines of code check whether you are in the right directory or not. The
above code gets all the packages. If any error occurs please check your spacing while adding
packages and also check that you have added the correct version of those packages.

8
DEPARTMENT OF INFORMATION TECHNOLOGY

CODE (main.dart):
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.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(
debugShowCheckedModeBanner: false,
title: 'Firestore Alerts',
home: FirestoreScreen(),
);
}
}

class FirestoreScreen extends StatefulWidget {


@override
_FirestoreScreenState createState() => _FirestoreScreenState();
}

class _FirestoreScreenState extends State<FirestoreScreen> {


final TextEditingController _textController = TextEditingController();
bool _isDataLoaded = false; // To prevent multiple snackbars when data is read

void _showSnackbar(BuildContext context, String message) {


ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(message),
duration: Duration(seconds: 10), // Increased duration
),
);
}

void _addData() {
String text = _textController.text.trim();
if (text.isNotEmpty) {
FirebaseFirestore.instance.collection('data').add({
'text': text,
'timestamp': DateTime.now(),
}).then((_) {
_showSnackbar(context, "Data added successfully!");
}).catchError((error) {
_showSnackbar(context, "Failed to add data: $error");

9
DEPARTMENT OF INFORMATION TECHNOLOGY

});
_textController.clear();
} else {
_showSnackbar(context, "Please enter some text!");
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.green,
title: Text("Firestore Read & Write"),
),
body: Column(
children: [
Padding(
padding: const EdgeInsets.all(10.0),
child: Row(
children: [
Expanded(
child: TextField(
controller: _textController,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: "Enter Data",
),
),
),
SizedBox(width: 10),
ElevatedButton(
onPressed: _addData,
child: Text("Add"),
style: ElevatedButton.styleFrom(backgroundColor: Colors.green),
),
],
),
),
Expanded(
child: StreamBuilder(
stream: FirebaseFirestore.instance
.collection('data')
.orderBy('timestamp', descending: true)
.snapshots(),
builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
}
if (!snapshot.hasData || snapshot.data!.docs.isEmpty) {
return Center(child: Text("No data available"));
}

10
DEPARTMENT OF INFORMATION TECHNOLOGY

// Show snackbar only once when data is first loaded


if (!_isDataLoaded) {
WidgetsBinding.instance.addPostFrameCallback((_) {
_showSnackbar(context, "Data loaded successfully!");
_isDataLoaded = true; // Mark as loaded to prevent multiple alerts
});
}

return ListView(
children: snapshot.data!.docs.map((document) {
return Card(
margin: EdgeInsets.symmetric(horizontal: 10, vertical: 5),
child: ListTile(
title: Text(document['text']),
),
);
}).toList(),
);
},
),
),
],
),
);
}
}

Output Screenshots:

11
DEPARTMENT OF INFORMATION TECHNOLOGY

Conclusion:
We have written and read data into/from firebase.

Lab Outcome 03:


We have analyzed and built production ready Flutter App by incorporating backend services and
deploying on Android / iOS

12

You might also like