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.
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.
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.
#flutter #mobile-app-development #firebase #firestore