【问题标题】:Flutter Firebase where query arrayContains in List [duplicate]Flutter Firebase where query arrayContains in List [重复]
【发布时间】:2021-09-11 05:04:06
【问题描述】:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class SearchPage extends StatefulWidget {
  @override
  _SearchPageState createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> with TickerProviderStateMixin {
  final searchController = TextEditingController();
  final _firestore = FirebaseFirestore.instance;
  static const defaultSearch = "";
  String search  = defaultSearch ;

  void dispose() {
    searchController.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    searchController.addListener(searchChanged);
  }

  searchChanged() {
    setState(() {
      search = searchController.text;
    });
  }

  @override
  Widget build(BuildContext context) {
    var tarifRef = _firestore
        .collection("vehicles")
        .where("models", arrayContains: search);

    return Scaffold(
      body: Container(
        child: ListView(
          children: <Widget>[
            Expanded(
              child: Container(
                height: MediaQuery.of(context).size.height * 0.08,
                margin: EdgeInsets.only(top: 25),
                child: Text(
                  "Vehicles",
                  style: TextStyle(
                      fontSize: 20, fontFamily: "Quando", color: Colors.indigo),
                ),
              ),
            ),
            Expanded(
              child: Container(
                margin: EdgeInsets.only(
                    top: 10.0, bottom: 10.0, right: 30, left: 30),
                child: TextField(
                  keyboardType: TextInputType.text,
                  decoration: InputDecoration(
                    prefixIcon: Icon(Icons.search),
                  ),
                  controller: searchController,
                ),
              ),
            ),
            Expanded(
              child: Container(
                height: MediaQuery.of(context).size.height * 0.50,
                child: StreamBuilder<QuerySnapshot>(
                  stream: tarifRef.snapshots(),
                  builder: (BuildContext context, AsyncSnapshot asyncsnapshot) {
                    if (asyncsnapshot.hasError) {
                      return Center(
                        child: Text("Error"),
                      );
                    } else {
                      if (asyncsnapshot.hasData) {
                        List<DocumentSnapshot> listOfDocumentSnapshot =
                            asyncsnapshot.data.docs;
                        return Flexible(
                          child: ListView.builder(
                            itemCount: listOfDocumentSnapshot.length,
                            itemBuilder: (context, index) {
                              return Card(
                                color: Colors.indigo,
                                child: ListTile(
                                  title: Text(
                                    "${listOfDocumentSnapshot[index]["name"]}",
                                    style: TextStyle(
                                      fontSize: 20,
                                      color: Colors.white,
                                    ),
                                  ),
                                  subtitle: Text(
                                    "${listOfDocumentSnapshot[index]["models"]}",
                                    style: TextStyle(
                                      fontSize: 15,
                                      color: Colors.white,
                                    ),
                                  ),
                                  trailing: IconButton(
                                    icon: Icon(
                                      Icons.delete,
                                      color: Colors.white,
                                    ),
                                    onPressed: () async {
                                      await listOfDocumentSnapshot[index]
                                          .reference
                                          .delete();
                                    },
                                  ),
                                ),
                              );
                            },
                          ),
                        );
                      } else {
                        return Center(
                          child: CircularProgressIndicator(),
                        );
                      }
                    }
                  },
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

这是我的所有代码,并且我在 Firebase 中有这样的数据库;

vehicles: [
      {
        "name": "Vehicle1",
        "models": ["bus", "plane", "motorcycle"]
      },
      {
        "name": "Vehicle2",
        "models": ["motorcycle", "sporcar", "plane"]
      },
      {
        "name": "Vehicle3",
        "models": ["motorcycle", "plane", "bus"]
      }
    ]

在此示例中,我可以从用户那里获取一个输入,我可以查询并显示包含此数据的列表,但我想查询列表中是否包含多个数据。

例如在此代码中,如果用户输入公共汽车,程序显示 Vehicle1 列表,但我希望用户可以输入多个数据,例如飞机和摩托车。所以当用户输入飞机和摩托车时,我希望它显示车辆 2 和车辆 3 的列表。

我尝试了很多不同的方法,但我找不到解决这个问题的适当方法。

【问题讨论】:

  • 您能否显示您希望从查询中返回的文档的屏幕截图?
  • 例如,如果用户输入公共汽车和飞机我想看到这个视图
  • 抱歉没说清楚;我的意思是 Firebase 控制台中的文档屏幕截图。
  • 我已经添加了我的 firebase 文档
  • 我对代码的期望是显示这些文档中的哪些包含输入的变量。在我当前的代码中,我只能使用 arrayContains 方法查询一个变量。但我想这样做;例如我有这样的列表 List searchList = ["bus", "plane"];我想要这种用法 var tarifRef = _firestore.collection("vehicles").where("models", arrayContains: searchList);但它不起作用。

标签: list firebase flutter google-cloud-firestore


【解决方案1】:

我想你在这里寻找arrayContainsAny

var tarifRef = _firestore
    .collection("vehicles")
    .where("models", arrayContainsAny: ["bus", "plane"]);

此查询将返回其models 数组包含"bus""plane" 或两者的文档。

另请参阅 Query.where 的 FlutterFire 文档。

【讨论】:

猜你喜欢
  • 2021-09-26
  • 2023-01-15
  • 1970-01-01
  • 2023-04-11
  • 1970-01-01
  • 2021-01-21
  • 1970-01-01
  • 1970-01-01
  • 2015-10-23
相关资源
最近更新 更多