0
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(),
                        );
                      }
                    }
                  },
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

This my all code and also I have database in Firebase like this;

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

In this example I can take one input from user, I can query and display which list includes this data but I want to query more than one data is in lists or not.

For example in this code if user input bus, program display Vehicle1 list but I want user can input more than one data such as plane and motorcycle. And so when the user input the plane and motorcycle, I want it to be displayed the list of Vehicle 2 and Vehicle 3.

I try a lot of different ways but I can't found proparly solution to this problem.

Firebase Documents1

Firebase Documents2

Firebase Documents3

6
  • Can you show a screenshot of a document you expect back from your query? Commented Jun 28, 2021 at 23:48
  • For example if user input bus and plane i want to see this view Commented Jun 29, 2021 at 10:33
  • Sorry for not being clearer; I meant a screenshot of a document from within the Firebase console. Commented Jun 29, 2021 at 13:02
  • I have added my firebase documents Commented Jun 30, 2021 at 10:13
  • My expectation from the code is to show which of these documents contains the entered variables. In my current code I can only query one variable with arrayContains method. But I want to do this; for example I have list like this List<String> searchList = ["bus", "plane"]; and I want this usage var tarifRef = _firestore.collection("vehicles").where("models", arrayContains: searchList); but its not work. Commented Jun 30, 2021 at 10:35

1 Answer 1

0

I think you're looking for arrayContainsAny here:

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

This query will return documents whose models array contains either "bus", "plane" or both.

Also see the FlutterFire documentation for Query.where.

Sign up to request clarification or add additional context in comments.

2 Comments

Is there a way I can return documents that contain only both?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.