Fetching Data From Firebase Database in Flutter

Fetching Data From Firebase Database in Flutter:

In Previous example or post we have learned integrating Firebase Database to flutter App. If you want to know more about integration click here. In This example we are going to learn fetching data from Firebase Database. To fetch data from Firebase Database we have to Follow the below procedure.

Fetching Data From Firebase Database:

Server side do this :

  • Integrate Flutter App with Firebase Database
  • Add List of Collections in Firebase Database

In Flutter App do this:

  • Using Firestore instance to fetch Data in Flutter App
  • Displaying the list to the user through UI in Flutter App.

Integrate Flutter App with Firebase Database:

In previous article we have learned Integrating Firebase Database with flutter. If you want to learn integration click here. After integrating Firebase Database with Flutter App. In Firebase Console Open your newly Created project then you will see below screen. Then click on create Database.

When you click on create database above it will show below screen. select start in test mode and  click on enable.

It will show below screen with add collection option. Click on Add Collection option to add “collection id ” as a name. Here in this example we are using  “carnames” as collection id using this collection id we are accessing/ Fetching Firebase database data in Flutter App. After entering the name click on next as shown in below screen.

When you click on next in above screen you will see below screen with following fields.

  1.  Document Id it will be generated automatically so click on Auto-Id to generate  it.
adding field names:
  1. name is a field name in Firebase Database but it is a key “name” in Flutter App. Here name is of type String and in value enter any car name here we entered “bmw” as shown in below screen
  2.  simillarly “votes” is a field in Firebase Database but it is a key “votes ” in flutter App. Here votes is of type number so enter any value in value place here we entered “0” (zero). as shown in below screen

Note: To add new field click on “+”  as you see in below screen. After entering all the values click on save to save this values in Firebase Database.

When you click on save in above screen. you will see below screen with collection id i.e “carnames” , with this   carnames  we are accessing/ fetching the data and  name value pairs along with auto generated Document Id as shown in below screen. 

Similarly add two more name value pairs as shown in below screens.

Till now we have completed server side task. Now we are going to coding part means Flutter App part to access/ fetch the data we created above.

Using Firestore instance to fetch Data in Flutter App: 

In below example code we are creating firestore instance inside build method by passing “carnames”  as collection id  we discussed this above. Firestore instance gets snapshots. using this firestore instance we are accessing/ fetching the data from Firebase Database.

Adding Dependency Package to pubspec.yaml file:

Use the below code to add dependency package to pubspec.yaml file:

dependencies:
cloud_firestore: ^0.8.2
Without adding this dependency package if you use firestore instance it will show error or exception. After adding the dependency package import cloud_firestore into your dart file.
 
import ‘package:cloud_firestore/cloud_firestore.dart’;

@override
Widget build(BuildContext context) {

return Scaffold(
appBar: AppBar(

title: Text(title),
),
body: StreamBuilder(

stream: Firestore.instance.collection('carnames').snapshots(),
builder: (context, snapshot){

if(!snapshot.hasData) return const Text('loading....');
return ListView.builder(
itemExtent: 80.0,
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) =>
_buildListItem(context, snapshot.data.documents[index]),

);
}

// This trailing comma makes auto-formatting nicer for build methods.
),
);
}

Displaying the list to the user through UI in Flutter App:

After fetching Data From Database means here we are getting the data list and now we are going to displaying as rows.

Widget _buildListItem(BuildContext context, DocumentSnapshot document ){
return ListTile(
title: Row(
children: [

Expanded(
child: Text(
document['name'],
style: Theme.of(context).textTheme.headline,
),
),
Container(
decoration: const BoxDecoration(
color: Color(0xffdd),
),
padding: const EdgeInsets.all(10.0),
child: Text(
document['votes'].toString(),
style: Theme.of(context).textTheme.display1,

),
),
],
),

);
}

Now we are going to perform some action when we tap on a name it’s number will increase by “+1” to  perform this task use below code.

onTap: (){
//print("should increase vots here");
document.reference.updateData({
'votes': document['votes'] + 1
}

);
},

Below is the complete Example Code to Fetching Data From Firebase Database in Flutter:

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(

theme: ThemeData(

primarySwatch: Colors.blue,
),

home: const MyHomePage(title: 'Car Brand Names'),
);
}
}

class MyHomePage extends StatelessWidget {
const MyHomePage({Key key, this.title}) : super(key: key);

final String title;

Widget _buildListItem(BuildContext context, DocumentSnapshot document ){
return ListTile(
title: Row(
children: [

Expanded(
child: Text(
document['name'],
style: Theme.of(context).textTheme.headline,
),
),
Container(
decoration: const BoxDecoration(
color: Color(0xffdd),
),
padding: const EdgeInsets.all(10.0),
child: Text(
document['votes'].toString(),
style: Theme.of(context).textTheme.display1,

),
),
],
),

onTap: (){
//print("should increase vots here");
document.reference.updateData({
'votes': document['votes'] + 1
}

);
},
);
}

@override
Widget build(BuildContext context) {

return Scaffold(
appBar: AppBar(

title: Text(title),
),
body: StreamBuilder(

stream: Firestore.instance.collection('carnames').snapshots(),
builder: (context, snapshot){

if(!snapshot.hasData) return const Text('loading....');
return ListView.builder(
itemExtent: 80.0,
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) =>
_buildListItem(context, snapshot.data.documents[index]),

);
}

// This trailing comma makes auto-formatting nicer for build methods.
),
);
}
}

Congratulations You Have Learned Fetching Data From Firebase Database in Flutter….!!!

If It Is HelpFul  Share It With Your Friends….!!!

If You Have Any Query Make A Comment….!!!

Leave a Reply

Categories

Myles [CPS] IN
Shein WW