0

我有一个日历功能作为食物日志,如果用户在该日历上选择特定日期,它将显示所有食物仅在该选定日期食用。

我的date字段是这样的时间戳格式January 1, 2022 at 12:00:00 AM UTC+8,它位于一个名为user_foodLog.

我想使用 streambuilder 根据日期获取数据,但我有点卡在where子句:

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

我只知道如何通过使用来检索今天的日期,DateTime.now()但是如果我想要 2 天前或上个月的数据怎么办?

更新:我正在使用table_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(),
                    ),
                  ),
                ),
]

我的日历看起来像这样,我想在日历下方的空间显示所选日期的数据。

4

1 回答 1

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

于 2022-01-10T08:24:14.640 回答