Firebase query data appears and disappears quickly - StreamBuilder

Viewed 72

I'm implementing a search functionality in the app. I'm using firebase where clause to filter the data

the filtered data appears for a second and it then disappeared immediately

here is my code


String searchName = "";

TextFormField(
              onChanged: (value){
                setState((){
                  searchName = value;
                });
              },
              decoration: InputDecoration(
                  hintText: 'SEARCH',
                  border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(25.0),
                      borderSide: BorderSide.none
                  )
              ),
            ),


StreamBuilder(
              stream: searchName != "" ? FirebaseFirestore.instance.collectionGroup('user_offers').where("fieldName", isEqualTo: searchName).snapshots() : FirebaseFirestore.instance.collectionGroup('user_offers').snapshots(),
              builder: (BuildContext context, AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot) {
                if(snapshot.hasData){
                  return ListView.builder() // returning a list
                }
                return const Center(child: CircularProgressIndicator(color: Colors.white));
              },
            ),

What am I doing wrong? The data appears for a second and it then disappears instantly

1 Answers

You should have to use two conditions 1st for the state (e.g. ConnectionState, waiting, done) and 2nd for null check. whenever you use FIREBASE WHERE you should always use null check. (e.g. if statement and then must else).

It's true snapshot parament have data. But snapshot.data!.docs have with null. You must check it (snapshot.data!.docs) with if else statement.

disappears instantly because you haven't checked snapshot.data!.docs with if else statement either empty or not empty.

I hope it could help.

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:towermarket/models/order.dart';

import '../order_details_screen.dart';

class InProgressOrders extends StatelessWidget {
  const InProgressOrders({
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
      stream: FirebaseFirestore.instance
          .collection("orders")
          .where("completed", isEqualTo: false)
          .snapshots(),
      builder:
          (_, AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot) {
        switch (snapshot.connectionState) {
          case ConnectionState.none:
          case ConnectionState.waiting:
            return const Center(
              child: CircularProgressIndicator(),
            );
          case ConnectionState.active:
          case ConnectionState.done:
            final List<Order> orders =
                snapshot.data!.docs.map((e) => Order.fromSnapshot(e)).toList();

            if (orders.isNotEmpty) {
              return ListView.builder(
                itemCount: orders.length,
                itemBuilder: (_, index) {
                  return ListTile(
                    onTap: () {
                      Navigator.push(context, OrderDetailsScreen.route());
                    },
                    leading: Text("${index + 1}"),
                    title: Text(orders[index].reference!),
                    subtitle: Text(orders[index].address),
                    trailing: Text("PKR ${orders[index].total}"),
                  );
                },
              );
            } else {
              return const Center(
                child: Text("No, In Progress Order"),
              );
            }

          default:
            return const Center(
              child: Text("Somethign went wrong"),
            );
        }
      },
    );
  }
}
Related