Flutterexperts

Empowering Vision with FlutterExperts' Expertise
Search Data In Flutter Using Cloud Firestore

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 contents:

:: 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 instructions given in this blog to connect your app with Firebase and create a collection on the cloud firestore.

Using Firebase Firestore in Flutter
Fetching data from cloud firestoremedium.com

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

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:

SearchDelegate class
Delegate for show search to define the content of the search page. The search page always shows an AppBar at the top…api.flutter.dev


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,
);
}

https://gist.github.com/anmolseth06/9840d5fb6856217324d1c86f2bad0258#file-searchdelegate-dart


Github Link

flutter-devs/search_feature_demo
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…github.com


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!.

Leave comment

Your email address will not be published. Required fields are marked with *.