简体   繁体   中英

flutter search in firestore for two items

I'm developing a flight ticket booking app with flutter and I'm trying to add a search query from Firestore for the start and destination. basically the idea is for the user to choose his starting and destination location by searching and when he select his starting station it will be stored in selected item and this particular item will not be found in the destination items no longer.

can you show me how to accomplish this task?

You can implement search text by using this code:

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:trackingsystem/Director/Director_View_Job_Details.dart';

class DirectorViewJob extends StatefulWidget {
  @override
  _DirectorViewJobState createState() => new _DirectorViewJobState();
}

class _DirectorViewJobState extends State<DirectorViewJob> {
  var jobTitle = [];
  var jobDescription = [];
  var jobSalary = [];
  var jobExperience = [];
  var jobDeadlineDate = [];
  var companyName = [];
  bool dataCheck = false;
  bool isLoading = false;
  var jobDetails;
  var id;

  var documnet = [];
  List products = [];
  var productId = [];
  var deleteTitle;

  void getJobs() async {
    setState(() {
      isLoading = true;
    });
    Firestore.instance
        .collection("CreateJob")
        .getDocuments()
        .then((querySnapshot) {
      querySnapshot.documents.forEach((result) {
        id = result.documentID;
        products.add(result.data['Job Details']);

        documnet.add(id);
        jobDetails = (result.data["Job Details"]);
        jobTitle.add(jobDetails['title']);
        jobDescription.add(jobDetails['description']);
        jobSalary.add(jobDetails['salary']);
        jobDeadlineDate.add(jobDetails['date']);
        print("date $jobDeadlineDate");

        jobExperience.add(jobDetails['Experience_Level']);
        companyName.add(jobDetails['companyName']);
        if (jobDetails.isNotEmpty) {
          setState(() {
            dataCheck = true;
          });
        } else {
          isLoading = true;
        }
      });
      setState(() {
        isLoading = false;
      });
    });
  }

  searchJob(q) {
    print(q);
    print('products $products');
    for (int i = 0; i < products.length; i++) {
      if (products[i]['title'] == "$q") {
        setState(() {
          jobTitle.clear();
          jobSalary.clear();
          jobDescription.clear();
          jobDeadlineDate.clear();
          jobTitle.add(products[i]['title']);
          jobDescription.add(products[i]["description"]);
          jobSalary.add(products[i]['salary']);
          jobDeadlineDate.add(products[i]['date']);
        });
      }
    }
  }

  @override
  void initState() {
    getJobs();

    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
          appBar: AppBar(
            backgroundColor: Colors.blueGrey[600],
            title: Text(
              "Jobs",
              style: TextStyle(fontFamily: 'Righteous'),
            ),
          ),
          backgroundColor: Colors.white,
          body: isLoading
              ? SpinKitDoubleBounce(
                  color: Colors.blueGrey,
                )
              : Center(
                  child: ListView(
                      children: dataCheck
                          ? <Widget>[
                              SizedBox(
                                height: 20,
                              ),
                              SizedBox(
                                height: 10,
                              ),
                              Container(
                                child: TextField(
//                controller: _searchQueryController,
                                  autofocus: true,
                                  decoration: InputDecoration(
                                    labelText: "Search Job",
                                    hintText: "Search",
                                    prefixIcon: Icon(
                                      Icons.search,
                                      color: Colors.blueGrey[400],
                                    ),
                                    fillColor: Colors.white,
                                    border: new OutlineInputBorder(
                                      borderRadius:
                                          new BorderRadius.circular(25.0),
                                      borderSide: new BorderSide(),
                                    ),
                                    //fillColor: Colors.green
                                  ),
                                  style: TextStyle(
                                      color: Colors.blueGrey[300],
                                      fontSize: 16.0),
                                  onChanged: (query) => {searchJob(query)},
                                ),
                              ),
                              SizedBox(
                                height: 10,
                              ),
                              Container(
                                decoration: BoxDecoration(
//                  color: Colors.lightGreen[100],
                                    ),
                                child: new ListView.builder(
                                    shrinkWrap: true,
                                    physics: BouncingScrollPhysics(),
                                    itemCount: jobTitle?.length ?? 0,
                                    itemBuilder: (BuildContext context, index) {
                                      return InkWell(
                                          splashColor: Colors.white,
                                          onTap: () async {
                                            Navigator.push(
                                              context,
                                              new MaterialPageRoute(
                                                  builder: (context) =>
                                                      DirectorJobDetails(
                                                        jobDetailName:
                                                            jobTitle[index],
                                                        jobDetailDescription:
                                                            jobDescription[
                                                                index],
                                                        jobDetailExperience:
                                                            jobExperience[
                                                                index],
                                                        jobDetailDate:
                                                            jobDeadlineDate[
                                                                index],
                                                        jobDetailSalary:
                                                            jobSalary[index],
                                                        jobDetailCompany:
                                                            companyName[index],
                                                        documentId:
                                                            documnet[index],
                                                      )),
                                            );
                                          },
                                          child: new Card(
                                              color: Colors.blueGrey[200],
                                              elevation: 5,
                                              shape: RoundedRectangleBorder(
                                                borderRadius:
                                                    BorderRadius.circular(30.0),
                                              ),
                                              child: Container(
                                                  decoration: BoxDecoration(),
                                                  child: ListTile(
                                                    leading: Icon(Icons.work,
                                                        size: 40),
                                                    title: Text(jobTitle[index],
                                                        style: TextStyle(
                                                          color: Colors.black,
                                                          fontSize: 23.0,
//                                    fontWeight: FontWeight.bold,
                                                          fontFamily:
                                                              'Righteous',
                                                          //decoration: TextDecoration.none
                                                        )),

                                                    subtitle: Row(children: [
                                                      SizedBox(
                                                        height: 10,
                                                      ),
                                                      Expanded(
                                                        child: Text(
                                                            "Salary : ${jobSalary[index]}",
                                                            style: TextStyle(
                                                              color:
                                                                  Colors.black,
                                                              fontSize: 18.0,
//                                    fontWeight: FontWeight.bold,
                                                              fontFamily:
                                                                  'Righteous',
                                                              //decoration: TextDecoration.none
                                                            )),
                                                      ),
                                                      Expanded(
                                                        child: Text(
                                                            "DeadLine Date : ${jobDeadlineDate[index]}",
                                                            style: TextStyle(
                                                              color:
                                                                  Colors.black,
                                                              fontSize: 18.0,
//                                    fontWeight: FontWeight.bold,
                                                              fontFamily:
                                                                  'Righteous',
                                                              //decoration: TextDecoration.none
                                                            )),
                                                      )
                                                    ]),
//
                                                  ))));
                                    }),
                              ),
                              SizedBox(
                                height: 20,
                              )
                            ]
                          : <Widget>[
                              Container(
                                  padding: EdgeInsets.fromLTRB(
                                      50.0, 100.0, 50.0, 50.0),
                                  child: Center(
                                    child: Text(
                                      "No Jobs are available",
                                      style: TextStyle(
                                        color: Colors.black,
                                        fontSize: 25.0,
                                        fontWeight: FontWeight.bold,
                                        fontFamily: 'Righteous',
                                        //decoration: TextDecoration.none
                                      ),
                                    ),
                                  ))
                            ]),
                )),

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

You can use limit in your code Like this: FirebaseFirestore.instance.collection('test').limit(2).get() and you'll get only two elements

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM