0

I have a calendar functions as food log where if user select a particular date on that calendar, it would show all the foods has been consumed only on that selected date.

My date field is in timestamp format like this January 1, 2022 at 12:00:00 AM UTC+8 and its in a subcollection named user_foodLog.

I want to use streambuilder to get the data based on the date but I kinda got stucked at where clause:

StreamBuilder(
                                  stream: FirebaseFirestore.instance
                                      .collection('foodLog')
                                      .doc(user.uid)
                                      .collection('user_foodLog')
                                      .where('date', isEqualTo: //what should be in here?? )
                                      .snapshots(),
                                  builder: (context,
                                      AsyncSnapshot<QuerySnapshot> snapshot) {
                                    if (!snapshot.hasData) {
                                      return Text(
                                        '<no data>',
                                      );
                                    } else {
                                      return ListView.builder(
                                          shrinkWrap: true,
                                          itemCount: snapshot.data.docs.length,
                                          itemBuilder: (BuildContext context,
                                              int index) {
                                            DocumentSnapshot ds = snapshot.data.docs[index];
                                            return ListTile(
                                              leading: Icon(
                                                  Icons.account_circle,
                                                  color: Colors.white,
                                                  size: 35),
                                              title: Text(
                                                ds['food_name'],
                                                style: TextStyle(
                                                  fontSize: 18,
                                                  color: Colors.white,
                                                  fontFamily:
                                                      'QuattrocentoSans',
                                                  fontWeight: FontWeight.bold,
                                                ),
                                              ),
                                              trailing: Text(
                                                ds['calorie'],
                                                style: TextStyle(
                                                  fontSize: 16,
                                                  color: Colors.white,
                                                  fontFamily:
                                                      'QuattrocentoSans',
                                                  fontWeight: FontWeight.bold,
                                                ),
                                              ),
                                            );
                                          });
                                    }
                                  })

I only know how to retrieve today's date by using DateTime.now() but what if I want the data from 2 days ago or last month?

Update: I'm using table_calendar widget to build the calendar

Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          SingleChildScrollView(
            child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Card(
                    clipBehavior: Clip.antiAlias,
                    margin: const EdgeInsets.all(10.0),
                    child: TableCalendar(
                      startingDayOfWeek: StartingDayOfWeek.monday,
                      firstDay: DateTime.utc(2020, 10, 16),
                      lastDay: DateTime.utc(2025, 10, 16),
                      focusedDay: _focusedDay,

                      selectedDayPredicate: (day) =>
                        isSameDay(day, _selectedDay),
                      onDaySelected: (selectedDay, focusedDay){
                        setState(() {
                          _selectedDay = selectedDay;
                          _focusedDay = focusedDay;
                        }
                        );
                      },
                      headerStyle: HeaderStyle(
                        headerMargin: const EdgeInsets.only(bottom: 8.0),
                        titleTextStyle: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 20,
                        )
                      ),
                      calendarStyle: CalendarStyle(),
                      calendarBuilders: CalendarBuilders(),
                    ),
                  ),
                ),
]

My calendar looks something like this and I want to display data of selected date at the space below the calendar.

jung_66
  • 41
  • 4

1 Answers1

0

Assuming you are using a the flutter show the date picker

DateTime selectedDate = DateTime.now();

Future<void> _selectDate(BuildContext context) async {
    final DateTime picked = await showDatePicker(
        context: context,
        initialDate: selectedDate,
        firstDate: DateTime(2015, 8),
        lastDate: DateTime(2101));
    if (picked != null && picked != selectedDate)
      setState(() {
        selectedDate = picked;
      });
fetchData(selectedDate);
  }

...

body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Text("${selectedDate.toLocal()}".split(' ')[0]),
            SizedBox(height: 20.0,),
            RaisedButton(
              onPressed: () => _selectDate(context),
              child: Text('Select date'),
            ),
          ],
        ),
      ),

...

now you can use selectedDate in your query

you cans separate your stream from the UI to be able to call it from anywhere

Stream mydata;

  fetchData(DateTime? dateTm){
var res =  FirebaseFirestore.instance
               .collection('foodLog')
                  .doc(user.uid)
                      .collection('user_foodLog')
                     .where('date', isEqualTo: dateTm )
                     
          .snapshots();
    setstate(({mydata=res;});
    
    }

here is a better ref, typing this offhead

griffins
  • 7,079
  • 4
  • 29
  • 54
  • I just updated my question by adding the table_calendar widget. Thats what im using to show the calendar. Based on your answer, since I already build the calendar, I only need to add the ```fetchData``` function into my codes right? Do you know which part of code in my ```table_calendar``` widget should I fit the fetchData function? And do I need to use listview.builder to display the result from fetchData? I'm very new to flutter hence the silly questions. Thank you btw. – jung_66 Jan 13 '22 at 00:33