简体   繁体   English

flutter 在 firestore 中搜索两个项目

[英]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.我正在开发一个带有 flutter 的机票预订应用程序,我正在尝试从 Firestore 添加一个搜索查询以获取起点和目的地。 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.基本上这个想法是让用户通过搜索选择他的起点和目的地位置,当他 select 他的起点站时,它将存储在所选项目中,并且不再在目的地项目中找到该特定项目。

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您可以像这样在代码中使用限制FirebaseFirestore.instance.collection('test').limit(2).get()并且您只会得到两个元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 Flutter 更新 Firestore 中的项目 - Updating items in Firestore using Flutter 在 FLutter 中加入两个 Firestore collections - Join two firestore collections in FLutter 如何使 Firestore 搜索结果显示在 flutter 中? - How to make firestore search results display in flutter? 从 flutter 监听 firestore 数据库中的两个 collections - Listen to two collections in firestore database from flutter 如何使用 Firebase Firestore 中的数据填充 Flutter 中的 DropdownButtonFormField 中的项目 - How to populate items in a DropdownButtonFormField in Flutter with data in Firebase Firestore Flutter - 如何使用 ListTile 显示从 Firebase Firestore 中提取的 ArrayList 项? - Flutter - How to show ArrayList items pulled from Firebase Firestore with ListTile? Flutter - 使用 Firestore 实例的 BuildSuggestions(搜索代理)出错 - Flutter - Error in BuildSuggestions (Search Delegate) using Firestore instance 如何使用 Flutter 在 Firestore 中存储文件夹列表并且每个文件夹都有项目列表 - How can I store a list of folders and each folder has list of items in Firestore using Flutter Flutter/Firestore:如何在滚动时将项目添加到 stream(完成获取后保留滚动位置)? - Flutter/Firestore: How to add items to stream on scroll (preserve scrollposition when done fetching)? firebase 消息传递和 Firestore 以及 flutter - firebase messaging and firestore and flutter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM