Cloud Firestore Flutter Tutorial

In this article, we are going to integrate cloud firestore in flutter application to store and sync data for both client and server side. You can also check out flutter firebase related articles.

In this flutter example, we are going to perform CRUD(create, read, update and delete) operations like sqlite database. First we will display workers list screen. From here we can add worker from add icon in app bar. We can edit worker information from edit icon and delete worker info using delete icon.

 

Create Firebase Project

First we need to create firebase project to integrate with our flutter application.

 
cloud firestore flutter

You can also enable google analytics if you want to track some information.

 
 
 
cloud firestore flutter
 
cloud firestore flutter
 
 

Add firebase to our android app

 
 
 
cloud firestore flutter
 
 

Add firebase to our iOS app

 
 
 
cloud firestore flutter
 
 

Create Cloud Firestore Database

 
 
 
 
 
 

Add required dependencies in your pubspec.yaml file

firebase_core: ^1.0.1
cloud_firestore: ^1.0.1
 
 

Initialize Firebase in flutter app

Future<FirebaseApp> initializeFirebaseApp() async {
FirebaseApp firebaseApp = await Firebase.initializeApp();
return firebaseApp;
}

body: FutureBuilder(
future: initializeFirebaseApp(),
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text(‘Error initializing Firebase’);
} else if (snapshot.connectionState == ConnectionState.done) {
return Container(
);
}
return CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(
Color(0xFFF57C00),
),
);
},
),

 
 

Create Model Class

class Worker {

String workerId, workerName, workerSalary, workerAge;

Worker({this.workerId, this.workerName, this.workerSalary, this.workerAge});

}

 
 

Write data in Cloud Firestore

final FirebaseFirestore firebaseFirestore = FirebaseFirestore.instance;
final CollectionReference workersCollectionReference = firebaseFirestore.collection(‘workers’);

static Future<void> addWorker({
@required Worker worker,
}) async {
DocumentReference documentReference =
workersCollectionReference.doc();

Map<String, dynamic> data = <String, dynamic>{
“name”: worker.workerName,
“salary”: worker.workerSalary,
“age”: worker.workerAge,
};

await documentReference
.set(data)
.whenComplete(() => print(“Worker added to the firestore”))
.catchError((e) => print(e));
}

 
 

Read Data from Flutter Cloud Firestore

static Stream<QuerySnapshot> getWorkers() {
return workersCollectionReference.snapshots();
}
 
 

Update Data in Firebase Firestore Flutter

static Future<void> updateWorker({
@required Worker worker,
}) async {
DocumentReference documentReference =
workersCollectionReference.doc(worker.workerId);

Map<String, dynamic> data = <String, dynamic>{
“name”: worker.workerName,
“salary”: worker.workerSalary,
“age”: worker.workerAge,
};

await documentReference
.update(data)
.whenComplete(() => print(“Worker updated in the firestore”))
.catchError((e) => print(e));
}

 
 

Delete data from Cloud Firestore Flutter

static Future<void> deleteWorker({
@required String workerId,
}) async {
DocumentReference documentReferencer =
workersCollectionReference.doc(workerId);

await documentReferencer
.delete()
.whenComplete(() => print(‘Worker deleted from the firestore’))
.catchError((e) => print(e));
}

 
 

Display data UI for firestore flutter

import ‘package:cloud_firestore/cloud_firestore.dart’;
import ‘package:firebase_core/firebase_core.dart’;
import ‘package:flutter/material.dart’;
import ‘package:fluttercloudfirestoresample/add_edit_worker_screen.dart’;
import ‘package:fluttercloudfirestoresample/firestore_helper.dart’;
import ‘worker.dart’;

class WorkersListScreen extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return WorkersListScreenState();
}
}

class WorkersListScreenState extends State<WorkersListScreen> {
List<Worker> listWorkers = [];

Future<FirebaseApp> initializeFirebaseApp() async {
FirebaseApp firebaseApp = await Firebase.initializeApp();
return firebaseApp;
}

@override
void initState() {
super.initState();
}

@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text(“Flutter Cloud Firestore Sample”),
actions: <Widget>[
IconButton(
icon: Icon(Icons.add),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => AddEditWorkerScreen(false)));
},
)
],
),
body: FutureBuilder(
future: initializeFirebaseApp(),
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text(‘Error initializing Firebase’);
} else if (snapshot.connectionState == ConnectionState.done) {
return StreamBuilder<QuerySnapshot>(
stream: FireStoreHelper.getWorkers(),
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text(‘Something went wrong’);
} else if (snapshot.hasData || snapshot.data != null) {
return Container(
padding: EdgeInsets.all(15),
child: ListView.separated(
separatorBuilder: (context, index) => SizedBox(height: 16.0),
itemCount: snapshot.data.docs.length,
itemBuilder: (context, position) {
var workersData = snapshot.data.docs[position].data();
var docID = snapshot.data.docs[position].id;
var getWorker = Worker(workerId: docID, workerName : workersData[‘name’], workerSalary : workersData[‘salary’], workerAge : workersData[‘age’]);
var salary = getWorker.workerSalary;
var age = getWorker.workerAge;
listWorkers.add(getWorker);
return Card(
elevation: 8,
child: Container(
height: 80,
padding: EdgeInsets.all(15),
child: Stack(
children: <Widget>[
Align(
alignment: Alignment.topLeft,
child: Text(getWorker.workerName, style: TextStyle(fontSize: 18))),
Align(
alignment: Alignment.centerRight,
child: Container(
margin: EdgeInsets.only(right: 45),
child: IconButton(
icon: Icon(Icons.edit),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) =>
AddEditWorkerScreen(
true,
getWorker)));
}),
),
),
Align(
alignment: Alignment.centerRight,
child: IconButton(
icon: Icon(Icons.delete),
onPressed: () {
FireStoreHelper.deleteWorker(workerId: getWorker.workerId);
setState(() => {
listWorkers.removeWhere(
(item) =>
item.workerId ==
getWorker.workerId)
});
}),
),
Align(
alignment: Alignment.bottomLeft,
child: Text(
“Salary: $salary | Age: $age”,
style: TextStyle(fontSize: 18))),
],
),
));
},
),
);
}
return CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(
Color(0xFFF57C00),
),
);
});
}
return CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(
Color(0xFFF57C00),
),
);
},
),
));
}
}

 
 

Add/Update data UI for flutter firestore

import ‘package:flutter/material.dart’;
import ‘package:fluttercloudfirestoresample/firestore_helper.dart’;
import ‘package:fluttercloudfirestoresample/worker.dart’;

import ‘workers_list_screen.dart’;

class AddEditWorkerScreen extends StatefulWidget {
bool isEdit;
Worker selectedWorker;

AddEditWorkerScreen(this.isEdit, [this.selectedWorker]);

@override
State<StatefulWidget> createState() {
return AddEditWorkerScreenState();
}
}

class AddEditWorkerScreenState extends State<AddEditWorkerScreen> {
TextEditingController nameController = TextEditingController();
TextEditingController salaryController = TextEditingController();
TextEditingController ageController = TextEditingController();

@override
Widget build(BuildContext context) {

if (widget.isEdit) {
nameController.text = widget.selectedWorker.workerName.toString();
salaryController.text = widget.selectedWorker.workerSalary.toString();
ageController.text = widget.selectedWorker.workerAge.toString();
}

return SafeArea(
child: Scaffold(
body: SingleChildScrollView(
child: Container(
margin: EdgeInsets.all(25),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text(“Worker Name:”, style: TextStyle(fontSize: 18)),
SizedBox(width: 20),
Expanded(
child: TextField(controller: nameController),
)
],
),
SizedBox(height: 60),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text(“Worker Salary:”, style: TextStyle(fontSize: 18)),
SizedBox(width: 20),
Expanded(
child: TextField(
controller: salaryController,
keyboardType: TextInputType.number),
)
],
),
SizedBox(height: 60),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text(“Worker Age:”, style: TextStyle(fontSize: 18)),
SizedBox(width: 20),
Expanded(
child: TextField(
controller: ageController,
keyboardType: TextInputType.number),
)
],
),
SizedBox(height: 100),
RaisedButton(
color: Colors.grey,
child: Text(“Submit”,
style: TextStyle(color: Colors.white, fontSize: 18)),
onPressed: () {
var getWorkerName = nameController.text;
var getWorkerSalary = salaryController.text;
var getWorkerAge = ageController.text;
if (getWorkerName.isNotEmpty &&
getWorkerSalary.isNotEmpty &&
getWorkerAge.isNotEmpty) {
if (widget.isEdit) {
Worker updateWorker = Worker(
workerId: widget.selectedWorker.workerId,
workerName: getWorkerName,
workerSalary: getWorkerSalary,
workerAge: getWorkerAge);
FireStoreHelper.updateWorker(worker: updateWorker);
} else {
Worker addWorker = Worker(
workerName: getWorkerName,
workerSalary: getWorkerSalary,
workerAge: getWorkerAge);
FireStoreHelper.addWorker(worker: addWorker);
}
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (_) => WorkersListScreen()),
(r) => false);
}
},
)
],
),
),
)
),
);
}
}

 
 
 
 
cloud firestore flutter
 
cloud firestore flutter
 

3 thoughts on “Cloud Firestore Flutter Tutorial

Leave a Reply