Home > Enterprise >  How can I get specific documents using conditions from flutter real-time database
How can I get specific documents using conditions from flutter real-time database

Time:10-29

This is the Realtime Firebase data

This is the Firebase data

In this pic, you can see data and only I want to show available items documents from the database. But it shows all the documents. I just want to show only available data. If you know how to do it to get once or using stream or any other solution so please help because I was stuck in it for 3 days.

Here is the body of the main page working

 class OrderMenu extends StatefulWidget {
      const OrderMenu({
        Key? key,
        required this.dbChild,
      }) : super(key: key);
    
      final String dbChild;
    
      @override
      _OrderMenuState createState() => _OrderMenuState();
    }
    
    class _OrderMenuState extends State<OrderMenu> {
      DatabaseReference db = FirebaseDatabase.instance.reference();
      User? curUser = FirebaseAuth.instance.currentUser;
    
      int? len;
      List<GetData>? data;
      Map<String, dynamic>? proceed;
      List<GetData>? AvailData;
    
      late List<bool>? avail = List.generate(
        len!,
        (index) => false,
      );
    
      @override
      Widget build(BuildContext context) {
        return StreamBuilder<List<GetData>>(
          stream: DataStreamPublisher(widget.dbChild).getMenuStream(),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              data = snapshot.data;
              len = data!.length;
              return SafeArea(
                child: SingleChildScrollView(
                  child: Container(
                    margin: EdgeInsets.symmetric(vertical: 10.0),
                    width: double.infinity,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(
                          width: double.infinity,
                          child: DataTable2(
                            showBottomBorder: true,
                            headingRowHeight: 40,
                            showCheckboxColumn: true,
                            sortAscending: true,
                            columnSpacing: 5,
                            dataRowHeight: 60,
                            dividerThickness: 2,
                            bottomMargin: 20.0,
                            checkboxHorizontalMargin: 5,
                            columns: [
                              DataColumn2(
                                size: ColumnSize.L,
                                label: Center(
                                  child: Text(
                                    "Item Name",
                                    style: TextStyle(
                                      fontSize: 16,
                                      fontWeight: FontWeight.w600,
                                    ),
                                  ),
                                ),
                              ),
                              DataColumn2(
                                size: ColumnSize.S,
                                label: Center(
                                  child: Text(
                                    "Price",
                                    style: TextStyle(
                                      fontSize: 16,
                                      fontWeight: FontWeight.w600,
                                    ),
                                  ),
                                ),
                              ),
                              DataColumn2(
                                size: ColumnSize.L,
                                label: Center(
                                  child: Text(
                                    "Quantity",
                                    style: TextStyle(
                                      fontSize: 16,
                                      fontWeight: FontWeight.w600,
                                    ),
                                  ),
                                ),
                              ),
                            ],
                            rows: List<DataRow>.generate(
                              data!.length,
                              (index) => DataRow2(
                                selected: avail![index],
                                onSelectChanged: (bool? value) {
                                  setState(() {
                                    avail![index] = value!;
                                  });
                                },
                                color: MaterialStateProperty.resolveWith<Color?>(
                                  (Set<MaterialState> states) {
                                    if (states.contains(MaterialState.selected)) {
                                      return Theme.of(context)
                                          .colorScheme
                                          .primary
                                          .withOpacity(0.08);
                                    }
                                    return null;
                                  },
                                ),
                                cells: [
                                  DataCell(
                                    Text(
                                      data![index].Juice_Name,
                                    ),
                                  ),
                                  DataCell(
                                    Center(
                                      child: Text(
                                        data![index].Price,
                                      ),
                                    ),
                                  ),
                                  DataCell(
                                    IncDecButton(),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              );
            } else if (snapshot.hasError) {
              return Center(
                child: Text(
                  'Add Item in Menu.',
                  style: TextStyle(
                    fontSize: 18,
                  ),
                ),
              );
            }
            return Center(
              child: const CircularProgressIndicator(),
            );
          },
        );
      }
    }

**This is stream of GetDataPublisher**

   

     class DataStreamPublisher {
      final String dbChild;
      DatabaseReference database = FirebaseDatabase.instance.reference();
      User? curUser = FirebaseAuth.instance.currentUser;
    
      DataStreamPublisher(this.dbChild);
    
      Stream<List<GetData>> getDataStream() {
        final dataStream = database.child(curUser!.uid).child(dbChild).onValue;
        final streamToPublish = dataStream.map((event) {
          final dataMap = Map<String, dynamic>.from(event.snapshot.value);
          final dataList = dataMap.entries.map((e) {
            return GetData.fromRTDB(Map<String, dynamic>.from(e.value));
          }).toList();
          return dataList;
        });
        return streamToPublish;
      }
    
      Stream<List<GetData>> getMenuStream() {
        final dataStream = database.child(curUser!.uid).child(dbChild).onValue;
        final streamToPublish = dataStream.map((event) {
          final dataMap = Map<String, dynamic>.from(event.snapshot.value);
          final dataList = dataMap.entries.map((e) {
            **if (e.value["Available"] == true) {
              print("Here I need a condition to get available data. OR any other possibility");
            }**
            return GetData.fromRTDB(Map<String, dynamic>.from(e.value));
          }).toList();
          return dataList;
        });
        return streamToPublish;
      }
    }

This is GetData class

class GetData {
      String Juice_Name;
      String Price;
      bool Available;
      var key;
    
      GetData({
        required this.Juice_Name,
        required this.Available,
        required this.Price,
        required this.key,
      });
    
      factory GetData.fromRTDB(Map<String, dynamic> data) {
        return GetData(
          Juice_Name: data['Juice_Name'] ?? 'Enter Juice Name',
          Price: data['Price'] ?? 'Enter Price',
          Available: data['Available'] ?? false,
          key: data['Key'] ?? 'key',
        );
      }
    }

CodePudding user response:

When you are using the following reference:

final dataStream = database.child(curUser!.uid).child(dbChild)

You will indeed get all the data under the "dbChild" node.

If you only need to get the objects that have the "Available" property set to true, then you should use a Query that look like this:

DatabaseReference db = FirebaseDatabase.instance.reference();
var query = db.child(curUser!.uid).child('Juices').orderByChild("Available").equalTo(true);
  • Related