Home > other >  show filtered data in. stream builder in flutter
show filtered data in. stream builder in flutter

Time:11-23

Learning purpose I have created a screen that showing firebase data based on transaction list..here I have added three text button for filtering data like

All : showing all records Income : showing only income transactions Expense : showing only expense transactions.

does it mean I have to make 3 future method? but what if I have many filter criteria...is there any other way...furthere I will date filter based on week month yearly...

class _HomeScreen2State extends State<HomeScreen2> {
  Stream _getAllEntries() {
    return FirebaseFirestore.instance
        .collection('users')
        .doc(widget.loggeduser.userid)
        .collection('expenses')
        .orderBy("date", descending: true)
        .snapshots();
  }

  @override
  Widget build(BuildContext context) {
    var size = MediaQuery.of(context).size;

    return Scaffold(
      appBar: showAppbar(),
      body: SafeArea(
          child: Column(
        children: [
          Padding(
            padding: EdgeInsets.all(10),
            child: Align(
              alignment: Alignment.centerLeft,
              child: Row(
                mainAxisSize: MainAxisSize.min,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  TextButton(onPressed: () {}, child: Text('All')),
                  TextButton(onPressed: () {}, child: Text('Expenses')),
                  TextButton(onPressed: () {}, child: Text('Income')),
                ],
              ),
            ),
          ),
          SizedBox(
            height: 10,
          ),
          showTransactions(size),
        ],
      )),
      floatingActionButton: buildfloatingactionbutton(),
    );
  }

  Widget showTransactions(Size size) {
    return Container(
      height: size.height * .65,
      // color: Colors.red,
      child: StreamBuilder(
          stream: _getAllEntries(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.active) {
              if (snapshot.hasData) {
                QuerySnapshot querysnapshot = snapshot.data as QuerySnapshot;
                if (querysnapshot.docs.length > 0) {
                  return ListView.builder(
                      padding: EdgeInsets.symmetric(vertical: 10),
                      itemCount: querysnapshot.docs.length,
                      itemBuilder: (context, index) {
                        final trans = TransactionModel.fromjson(
                            querysnapshot.docs[index].data()
                                as Map<String, dynamic>);
                        return TransactionCard(
                          ontap: () async {},
                          amount: trans.amount.toStringAsFixed(2),
                          datetime: trans.date.toString(),
                          paymentby: trans.paymentmode,
                          category: trans.category.title,
                          categoryicon: trans.category.iconurl,
                          isexpense: trans.isexpense,
                        );
                      }); //listview end
                } else {
                  return Container(
                      child: Center(child: Text('No Transaction Found...')));
                }
              } else {
                if (snapshot.hasError) {
                  return Text('error found');
                } else {
                  return Text('empty..');
                }
              }
            } else {
              return Center(child: CircularProgressIndicator());
            }
          }),
    );
  }

CodePudding user response:

Add a new variable that will tell flutter about your filter

String myFilter = "all"; // *** or 'Expenses' or 'Income'

Then use that new variable in your stream definition:

  Stream _getAllEntries(String myFilter ) {
    return FirebaseFirestore.instance
        .collection('users')
        .doc(widget.loggeduser.userid)
        .collection(myFilter) //*** see change... or use a filter ***
        .orderBy("date", descending: true)
        .snapshots();
  }

Then update the value of your filter, in each one of your 3 buttons:

TextButton(onPressed: () {
  setState(() {
    myFilter = "all";
  });
}, child: Text('All')),

Finally, update the call to your stream:

child: StreamBuilder(
          stream: _getAllEntries(myFilter),
  • Related