dart Flutter:Firebase基本查询或基本搜索代码

e37o9pze  于 2022-12-25  发布在  Flutter
关注(0)|答案(8)|浏览(177)

主要概念是显示包含搜索字母表的文档或字段。
搜索栏得到给定的输入,它发送到_firebasesearch(),但在返回什么也没有出来,上面的图像是我的数据库结构,试图弄清楚一个多星期。

    • 代码**
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter_search_bar/flutter_search_bar.dart';

SearchBar searchBar;
GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

class DisplayCourse extends StatefulWidget {
  @override
  _DisplayCourseState createState() => new _DisplayCourseState();
}

AppBar _buildAppBar(BuildContext context) {
  return new AppBar(
    title: new Text("FIREBASE QUERY"),
    centerTitle: true,
    actions: <Widget>[
      searchBar.getSearchAction(context),
    ],
  );
}

class _DisplayCourseState extends State<DisplayCourse> {
  String _queryText;

  _DisplayCourseState() {
    searchBar = new SearchBar(
      onSubmitted: onSubmitted,
      inBar: true,
      buildDefaultAppBar: _buildAppBar,
      setState: setState,
    );
  }

  void onSubmitted(String value) {
    setState(() {
      _queryText = value;
      _scaffoldKey.currentState.showSnackBar(new SnackBar(
        content: new Text('You have Searched something!'),
        backgroundColor: Colors.yellow,
      ));
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      key: _scaffoldKey,
      appBar: searchBar.build(context),
      backgroundColor: Colors.red,
      body: _fireSearch(_queryText),
    );
  }
}

Widget _fireSearch(String queryText) {
  return new StreamBuilder(
    stream: Firestore.instance
    .collection('courses')
    .where('title', isEqualTo: queryText)
    .snapshots(),
    builder: (context, snapshot) {
      if (!snapshot.hasData) return new Text('Loading...');
      return new ListView.builder(
        itemCount: snapshot.data.documents.length,
        itemBuilder: (context, index) =>
            _buildListItem(snapshot.data.documents[index]),
      );
    },
  );
}

Widget _buildListItem(DocumentSnapshot document) {
  return new ListTile(
    title: document['title'],
    subtitle: document['subtitle'],
  );
}
    • 主要概念是显示包含搜索字母表的文档排序字段**

搜索栏得到给定的输入,它发送到_firebasesearch(),但返回什么也没有出来,上面的图像是我的数据库结构,试图弄清楚一个多星期,

l0oc07j2

l0oc07j21#

这听起来可能是一个荒谬的解决方案,但实际上工作得非常好,它几乎就像SQL中的Like '%'查询
在文本字段中,当您在where()isGreaterThanOrEqualTowill内键入值时,将其与大于输入的所有字符串值进行比较,如果您在结尾处连接“Z”,则
isLessThan
将在您的搜索关键字之后结束,并且您从firestore获得所需的结果。

// Declare your searchkey and Stream variables first
String searchKey;
Stream streamQuery;

TextField(
              onChanged: (value){
                  setState(() {
                    searchKey = value;
                    streamQuery = _firestore.collection('Col-Name')
                        .where('fieldName', isGreaterThanOrEqualTo: searchKey)
                        .where('fieldName', isLessThan: searchKey +'z')
                        .snapshots();
                  });
    }),

我在StreamBuilder中使用了这个流,它完全按照预期工作。

限制:

1.搜索区分大小写(如果数据一致,如Type Case,则可以将searchKey转换为特定大小写)
1.你必须从第一个字母开始搜索,它不能从中间搜索

jmp7cifd

jmp7cifd2#

我说得有点晚了,但我只想分享一些我是如何实现搜索功能而不使用第三方应用程序的。我的解决方案是使用firestore直接查询。下面是代码:

Future<List<DocumentSnapshot>> getSuggestion(String suggestion) =>
  Firestore.instance
      .collection('your-collection')
      .orderBy('your-document')
      .startAt([searchkey])
      .endAt([searchkey + '\uf8ff'])
      .getDocuments()
      .then((snapshot) {
        return snapshot.documents;
      });

例如,如果你想搜索所有包含“ab”的关键字,那么它将显示所有包含“ab”的单词(例如abcd,abde,abwe)。如果你想使自动建议搜索功能,你可以使用打印头。这可以在这个链接中找到:https://pub.dev/packages/flutter_typeahead
祝你好运。

sh7euo9m

sh7euo9m3#

您不必重建整个流,只需根据您的搜索字符串过滤流中的结果。快速,无需重建整个流,查找搜索字符串的示例,不仅从单词的开头,而且不区分大小写。

return StreamBuilder(
  stream: FirebaseFirestore.instance.collection("shops").snapshots(),
  builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {

    if (snapshot.hasError)  // TODO: show alert
      return Text('Something went wrong');

    if (snapshot.connectionState == ConnectionState.waiting)
      return Column(
        children: [
          Center(
              child: CupertinoActivityIndicator()
          )
        ],
      );

    var len = snapshot.data.docs.length;
    if(len == 0)
      return Column(
        children: [
          SizedBox(height: 100),
          Center(
            child: Text("No shops available", style: TextStyle(fontSize: 20, color: Colors.grey)),
          )
        ],
      );

    List<Shop> shops = snapshot.data.docs.map((doc) => Shop(
        shopID: doc['shopID'],
        name: doc['name'],
        ...
    )).toList();
    shops = shops.where((s) => s.name.toLowerCase().contains(searchString.text.toLowerCase())).toList();
    
    
    return
        Expanded(
          child: ListView.builder(
              padding: EdgeInsets.symmetric(vertical: 15),
              scrollDirection: Axis.vertical,
              shrinkWrap: true,
              itemCount: shops.length,
              itemBuilder: (context, index) {
                return shopRow(shops[index]);
              }
          ),
        );
  },
);
l2osamch

l2osamch4#

问题是您期望从firestore得到title is equal to queryText而不是title contains queryText的结果。
如果您想要搜索功能,您可以在类似List<Model> model的变量中使用get and store the firestore documents,而不是上面存储的型号列表中的StreamBuilderimplement search manually

kadbb459

kadbb4595#

我找到的解决方案是:

List<String> listaProcura = List();
    String temp = "";
    for(var i=0;i<nomeProduto.length; i++) {
      if(nomeProduto[i] == " ") {
        temp = "";
      } else {
        temp = temp + nomeProduto[i];
        listaProcura.add(temp);
      }
    }

“listaProcura”是列表的名称。字符串“temp”是临时字符串的名称。这样,您将在firebase数据库中保存此名称列表。如下所示:

[0] E
  [1] Ex
  [2] Exa
  [3] Exam
  [4] Examp
  [5] Exampl
  [6] Example
  [7] o
  [8] on
  [9] one

要使用要搜索的词检索此信息:

await Firestore.instance.collection('name of your collection').where('name of your list saved in the firebase', arrayContains: 'the name you are searching').getDocuments();

这样,如果您搜索“one”并且名称为“Example one”,搜索将正确返回。

2ekbmq32

2ekbmq326#

这是另一个搜索代码,将在FIREBASE数据库中进行搜索

import 'package:flutter/material.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:firebase_database/ui/firebase_animated_list.dart';

class Db extends StatefulWidget {
  @override
  HomeState createState() => HomeState();
}

class HomeState extends State<Db> {
  List<Item> Remedios = List();
  Item item;
  DatabaseReference itemRef;
  TextEditingController controller = new TextEditingController();
  String filter;

  final GlobalKey<FormState> formKey = GlobalKey<FormState>();

  @override
  void initState() {
    super.initState();
    item = Item("", "");
    final FirebaseDatabase database = FirebaseDatabase.instance; //Rather then just writing FirebaseDatabase(), get the instance.
    itemRef = database.reference().child('Remedios');
    itemRef.onChildAdded.listen(_onEntryAdded);
    itemRef.onChildChanged.listen(_onEntryChanged);
    controller.addListener(() {
  setState(() {
    filter = controller.text;
  });
});
  }

  _onEntryAdded(Event event) {
    setState(() {
      Remedios.add(Item.fromSnapshot(event.snapshot));
    });
  }

  _onEntryChanged(Event event) {
    var old = Remedios.singleWhere((entry) {
      return entry.key == event.snapshot.key;
    });
    setState(() {
      Remedios\[Remedios.indexOf(old)\] = Item.fromSnapshot(event.snapshot);
    });
  }

  void handleSubmit() {
    final FormState form = formKey.currentState;

    if (form.validate()) {
      form.save();
      form.reset();
      itemRef.push().set(item.toJson());
    }
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        centerTitle: true,
        backgroundColor: new Color(0xFFE1564B),
      ),
      resizeToAvoidBottomPadding: false,
      body: Column(
        children: <Widget>\[
          new TextField(
          decoration: new InputDecoration(
          labelText: "Type something"
          ),
          controller: controller,
          ),
          Flexible(
            child: FirebaseAnimatedList(
              query: itemRef,
              itemBuilder: (BuildContext context, DataSnapshot snapshot,
                  Animation<double> animation, int index) {
                return  Remedios\[index\].name.contains(filter) || Remedios\[index\].form.contains(filter) ? ListTile(
                  leading: Icon(Icons.message),
                  title: Text(Remedios\[index\].name),
                  subtitle: Text(Remedios\[index\].form),
                ) : new Container();
              },
            ),
          ),
        \],
      ),
    );
  }
}

class Item {
  String key;
  String form;
  String name;

  Item(this.form, this.name);

  Item.fromSnapshot(DataSnapshot snapshot)
      : key = snapshot.key,
        form = snapshot.value\["form"\],
        name = snapshot.value\["name"\];

  toJson() {
    return {
      "form": form,
      "name": name,
    };
  }
}
mzmfm0qo

mzmfm0qo7#

如果搜索列表区分大小写,如下所示:

  1. Curaprox Be You显示器
  2. Curaprox黑白显示器
  3. Curaprox黑白微型显示器
  4. Curaprox超声专业显示器
  5. Curaprox大型齿间刷显示器
    然后:
response = await FirebaseFirestore.instance
                .collection('pointOFSale')
                .orderBy("title")
                .startAt([val.capitalize()]).endAt(
                    [val[0].toUpperCase() + '\uf8ff']).get();

扩展代码:

extension StringExtension on String {
        String capitalize() {
          return "${this[0].toUpperCase()}${this.substring(1)}";
        }
      }

如果列表类似于:

  1. Curaprox是你展示的吗
  2. curaprox黑白显示器
  3. curaprox黑白迷你显示器
    然后:
response = await FirebaseFirestore.instance
                .collection('pointOFSale')
                .orderBy("title")
                .startAt([val]).endAt([val + '\uf8ff']).get();
798qvoo8

798qvoo88#

如此简单和快速。

if (text.length > 1) {
  setState(() {
    tempSearchStore = _listPkh.documents.where((d) {
      if (d['nama'].toLowerCase().indexOf(text) > -1) {
        return true;
      } else if (d['alamat'].toLowerCase().indexOf(text) > -1) {
        return true;
      }
      return false;
    }).toList();
  });
} else {
  setState(() {
    tempSearchStore = _listPkh.documents;
  });
}

相关问题