【问题标题】:How can I fetch data from Firebase based on the selected date on calendar?如何根据日历上的选定日期从 Firebase 获取数据?
【发布时间】:2022-01-10 07:57:12
【问题描述】:

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

我的 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() 检索今天的日期,但如果我想要两天前或上个月的数据怎么办?

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

我的日历看起来像this,我想在日历下方的空白处显示选定日期的数据。

【问题讨论】:

    标签: flutter datetime flutter-streambuilder


    【解决方案1】:

    假设您使用的是颤振显示日期选择器

    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'),
                ),
              ],
            ),
          ),
    

    ...

    现在您可以在查询中使用selectedDate

    您可以将流与 UI 分开,以便能够从任何地方调用它

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

    这里有更好的ref, typing this offhead

    【讨论】:

    • 我刚刚通过添加 table_calendar 小部件更新了我的问题。那就是我用来显示日历的东西。根据您的回答,既然我已经构建了日历,我只需要将 fetchData 函数添加到我的代码中,对吗?你知道我的table_calendar 小部件中的哪一部分代码应该适合 fetchData 函数吗?我是否需要使用 listview.builder 来显示 fetchData 的结果?我对扑腾很陌生,因此提出了一些愚蠢的问题。顺便说一句,谢谢。
    猜你喜欢
    • 2015-07-06
    • 2019-12-08
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    相关资源
    最近更新 更多