Search Data In Flutter Using Cloud Firestore

Implementing Search using SearchDelegate In Flutter

Anmol Gupta
Jul 20 · 4 min read
Image for post
Search Feature In Flutter

Introduction

In this blog, we shall discuss about the search feature using database and locally in our app. I will use both cloud firestore and realtime database to implement a search feature. This feature is a very common feature in production applications nowadays. It also enhances the app standard and make it more productive. It also saves the user time.


Table of content :

:: Using cloud firestore

:: Using search Delegate

:: Github link


Importance of Search Feature in an app :

:: It saves the time of the user to find any object/Item

:: Provides transparency about the searched title

:: Improves the standard of the app

:: User-friendly, interactive, easy to use


Using cloud firestore

Here in this section, we will learn how to search for data on the cloud Firestore. First, we will create a collection of data on the cloud firestore, then we will use it to perform a search of items in our app.


Create a collection on cloud firestore

You can follow the instruction given in this blog to connect your app with firebase and create a collection on the cloud firestore.

Here I have created a collection of items with name, imageUrl, and searchKeywords.

Image for post
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';

class CloudFirestoreSearch extends StatefulWidget {
@override
_CloudFirestoreSearchState createState() => _CloudFirestoreSearchState();
}

class _CloudFirestoreSearchState extends State<CloudFirestoreSearch> {
String name = "";

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back_ios),
onPressed: () {
Navigator.of(context).pop();
},
),
title: Card(
child: TextField(
decoration: InputDecoration(
prefixIcon: Icon(Icons.search), hintText: 'Search...'),
onChanged: (val) {
setState(() {
name = val;
});
},
),
),
),
body: StreamBuilder<QuerySnapshot>(
stream: (name != "" && name != null)
? Firestore.instance
.collection('items')
.where("searchKeywords", arrayContains: name)
.snapshots()
: Firestore.instance.collection("items").snapshots(),
builder: (context, snapshot) {
return (snapshot.connectionState == ConnectionState.waiting)
? Center(child: CircularProgressIndicator())
: ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) {
DocumentSnapshot data = snapshot.data.documents[index];
return Card(
child: Row(
children: <Widget>[
Image.network(
data['imageUrl'],
width: 150,
height: 100,
fit: BoxFit.fill,
),
SizedBox(
width: 25,
),
Text(
data['name'],
style: TextStyle(
fontWeight: FontWeight.w700,
fontSize: 20,
),
),
],
),
);
},
);
},
),
);
}

}

Here we are using to control our screen view if the user search any item then the keyword entered by the user is set to name the variable then if inside the item collection searchKeyword array contains the keyword entered by the users then the data related to it flows through the stream and displayed on the screen.

This is the stream that we will use to see the search item or items.

Firestore.instance.collection('items').where("searchKeywords", arrayContains: name).snapshots()

Using the search Delegate

SearchDelegate is a pre-defined class inside the material.dart. This class provides us a predesigned search delegate. This class uses the following method to control the various operation to be performed to search for various items.

You can read about the method from the following link:


buildAction method

This method returns the list of widgets to display after the search query in the AppBar.

List<Widget> buildActions(BuildContext context) {
return [
IconButton(
icon: Icon(Icons.close),
onPressed: () {
close(context, null);
},
),
];
}

close(context, null) method is used to close the searchDelegate.


buildLeading method

Return a leading widget that is displayed before the query.

Widget buildLeading(BuildContext context) {
return IconButton(
icon: Icon(Icons.arrow_back_ios),
onPressed: () {
close(context, null);
},
);
}

buildResult method

This method is used to build the result based on the keyword entered by the user.

 Widget buildResults(BuildContext context) {
return Center(
child: Text(
query,
style: TextStyle(
color: Colors.blue, fontWeight: FontWeight.w900, fontSize: 30),
),
);
}

buildSuggestions method

This method builds the suggestion list base on the keyword entered by the user as a query.

Widget buildSuggestions(BuildContext context) {
List<Item> items = [
Item(title: 'apple'),
Item(title: 'mango'),
Item(title: 'banana'),
Item(title: 'pineapple'),
Item(title: 'orange'),
Item(title: 'oranges'),
];
List<Item> suggestionList = query.isEmpty
? items
: items.where((element) => element.title.startsWith(query)).toList();
return suggestionList.isEmpty
? Text("no result found")
: ListView.builder(
itemBuilder: (context, index) {
return ListTile(
title: Text(suggestionList[index].title),
onTap: () {
showResults(context);
},
);
},
itemCount: suggestionList.length,
);
}
searchDelegate.dart


Conclusion

The search feature is very useful, we learned how to search for data using a search delegate it provides us a predefined architecture to perform searching easily and conveniently. We can also search for data from our database. The basic fundamental concept of both searches is the same.

I hope this article has provided you with content information about what’s all about the topic, and you will give it — a Try. Initiate using Search feature for your apps. !!!


🌸🌼🌸 Thank you for reading. 🌸🌼🌸🌼


Feel free to connect with us:
And read more articles from FlutterDevs.com

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.

Image for post

FlutterDevs

FlutterDevs intent to deliver Flutter apps with high…

Anmol Gupta

Written by

FLUTTER DEVELOPER 🤷‍♂️🤷‍♂️

FlutterDevs

FlutterDevs intent to deliver Flutter apps with high quality. We’ve adopted Design First attitude which helps us deliver applications of highest quality.

Anmol Gupta

Written by

FLUTTER DEVELOPER 🤷‍♂️🤷‍♂️

FlutterDevs

FlutterDevs intent to deliver Flutter apps with high quality. We’ve adopted Design First attitude which helps us deliver applications of highest quality.