Flutter 如何从firestore获取数据并自动刷新状态而无需点击

Flutter 如何从firestore获取数据并自动刷新状态而无需点击,flutter,google-cloud-firestore,Flutter,Google Cloud Firestore,我正在使用CalendarCarousel小部件,并尝试从CloudFireStore添加事件。 我成功地从firebase获取了日期,问题是只有在单击任何日期后才可见,因此当用户第一次查看日历时,服务器端没有关于事件的信息。 如果返回到父级并返回日历,屏幕也会刷新。 如何刷新日历上的数据?我在网上浏览,只找到了使用ListView的示例 仅当我单击按钮时,才会显示firebase数据。(或当返回到父对象并返回时)如gif中所示 导入“包装:颤振/材料.省道”; 导入“package:fath

我正在使用CalendarCarousel小部件,并尝试从CloudFireStore添加事件。 我成功地从firebase获取了日期,问题是只有在单击任何日期后才可见,因此当用户第一次查看日历时,服务器端没有关于事件的信息。 如果返回到父级并返回日历,屏幕也会刷新。 如何刷新日历上的数据?我在网上浏览,只找到了使用ListView的示例

仅当我单击按钮时,才会显示firebase数据。(或当返回到父对象并返回时)如gif中所示

导入“包装:颤振/材料.省道”;
导入“package:father_home_flatter/model/constants.dart”;
导入“package:flatter_calendar_carousel/classes/event.dart”;
导入“package:flatter_calendar_carousel/classes/event_list.dart”;
导入“包:颤振日历旋转木马/颤振日历旋转木马.dart”
显示日历转盘;
导入“包:cloud_firestore/cloud_firestore.dart”;
类ScreenCalendar扩展StatefulWidget{
@凌驾
_ScreenCalendarState createState()=>new_ScreenCalendarState();
}
类_ScreenCalendarState扩展状态{
静态字符串noEventText=“Сбббббббб”;
字符串tabBarTitle=“日历”;
字符串calendarText=noEventText;
DateTime _currentDate=DateTime.now();
颜色_colorButtonColor=Colors.indigo;
颜色_colorTextButtonColor=Colors.black;
Color\u colorTextTodayButton=Colors.white;
静态常量字符串\u calendarRussian=“calendarRussian”;
静态常量字符串_eventTitle=“eventTitle”;
静态常量字符串_eventDay=“eventDay”;
静态常量字符串_eventMonth=“eventMonth”;
静态常量字符串_eventYear=“eventYear”;
void getCalendarEventList(){
Firestore.instance.collection(_).snapshots().listen((数据)=>
data.documents.forEach((doc)=>\u markedDateMap.add(
新日期时间(int.parse(doc[\u eventYear]),
int.parse(doc[\u eventMonth])、int.parse(doc[\u eventDay]),
新事件(
日期:新的日期时间(int.parse(doc[\u eventYear]),
int.parse(doc[\u eventMonth])、int.parse(doc[\u eventDay]),
标题:doc[\u eventTitle],
图标:_eventIcon))
//context.setState(()=>refresh(DateTime.now())}
));
}
@凌驾
void initState(){
getCalendarEventList();
super.initState();
}
@凌驾
小部件构建(构建上下文){
返回脚手架(
appBar:appBar(
标题:正文(
塔巴蒂特尔,
样式:Constants.myTextStyleAppBar,
),
iconTheme:Constants.myIconThemeDataAppBar,
高程:Constants.MyLevationAppBar,
backgroundColor:Constants.myAppBarColor,
),
正文:SingleChildScrollView(
子项:列(子项:[
卡片(
孩子:日历旋转木马(
weekendTextStyle:TextStyle(
颜色:颜色,红色,
),
周格式:假,
selectedDateTime:\u currentDate,
markedDatesMap:_markedDateMap,
selectedDayBorderColor:Colors.transparent,
SelectedDayButton颜色:颜色。靛蓝[300],
todayTextStyle:
TextStyle(颜色:Colors.black,fontwweight:fontwweight.bold),
selectedDayTextStyle:TextStyle(颜色:_colorTextButtonColor),
todayBorderColor:Colors.indigo,
weekdayTextStyle:TextStyle(颜色:Colors.black),
高度:420.0,
Daysharder:是的,
今天的按钮颜色:Colors.transparent,
地点:“RUS”,
onDayPressed:(日期时间日期,列出事件){
此.setState(()=>刷新(日期));
},
)),
卡片(
子:容器(
孩子:填充(
填充:来自LTRB(16.0,16.0,16.0,16.0,16.0)的边缘设置,
儿童:中心(
子:文本(
日历文本,
样式:Constants.textStyleCommonText,
)))))
])));
}
无效刷新(日期时间日期){
_currentDate=日期;
打印('所选日期'+
date.day.toString()+
date.month.toString()+
date.year.toString()+
' ' +
date.toString());
如果(_标记日期映射
.getEvents(新的日期时间(date.year、date.month、date.day))
.isNotEmpty){
calendarText=\u markedDateMap
.getEvents(新日期时间(date.year、date.month、date.day))[0]
标题
}否则{
calendarText=noEventText;
}
如果(日期==\u当前日期){
_colorButtonColor=Colors.indigo;
_colorTextButtonColor=Colors.white;
_colorTextTodayButton=Colors.white;
}否则{
_colorTextButtonColor=Colors.indigo;
_colorTextTodayButton=Colors.black;
}
}
}
事件列表_markedDateMap=新事件列表(事件:{
新日期时间(2019年1月24日):[
新事件(
日期:新日期时间(2019年1月24日),
标题:“奥勒姆·伊普苏姆·多洛·西特·阿梅特,献身于和平的精英”
“这是一个临时的劳动和就业机会。”
“\n\nUt enim ad minim veniam,”
“ullamco laboris nisi and aliquid ex ea commodi consequat.”
“\n\n在无教区的情况下,您可以自由选择是否为他人辩护。”
“除非是丘比特人,否则不可轻率行事,因为他是罪魁祸首,理应承担所有动物的劳动。”,
图标:_eventIcon,
)
]
});
Widget\u eventIcon=新容器(
装饰:新盒子装饰(
颜色:颜色,白色,
borderRadius:borderRadius.all(
import 'package:flutter/material.dart';
import 'package:father_home_flutter/model/constants.dart';
import 'package:flutter_calendar_carousel/classes/event.dart';
import 'package:flutter_calendar_carousel/classes/event_list.dart';
import 'package:flutter_calendar_carousel/flutter_calendar_carousel.dart'
    show CalendarCarousel;
import 'package:cloud_firestore/cloud_firestore.dart';

class ScreenCalendar extends StatefulWidget {
  @override
  _ScreenCalendarState createState() => new _ScreenCalendarState();
}

class _ScreenCalendarState extends State<ScreenCalendar> {
  static String noEventText = "Событий нет";
  String tabBarTitle = "Calendar";
  String calendarText = noEventText;
  DateTime _currentDate = DateTime.now();
  Color _colorButtonColor = Colors.indigo;
  Color _colorTextButtonColor = Colors.black;
  Color _colorTextTodayButton = Colors.white;

  static const String _calendarRussian = "calendarRussian";
  static const String _eventTitle = "eventTitle";

  static const String _eventDay = "eventDay";
  static const String _eventMonth = "eventMonth";
  static const String _eventYear = "eventYear";

  void getCalendarEventList() {
    Firestore.instance.collection(_calendarRussian).snapshots().listen((data) =>
        data.documents.forEach((doc) => _markedDateMap.add(
                new DateTime(int.parse(doc[_eventYear]),
                    int.parse(doc[_eventMonth]), int.parse(doc[_eventDay])),
                new Event(
                    date: new DateTime(int.parse(doc[_eventYear]),
                        int.parse(doc[_eventMonth]), int.parse(doc[_eventDay])),
                    title: doc[_eventTitle],
                    icon: _eventIcon))
//            context.setState(() => refresh(DateTime.now()))}
            ));
  }

  @override
  void initState() {
    getCalendarEventList();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(
            tabBarTitle,
            style: Constants.myTextStyleAppBar,
          ),
          iconTheme: Constants.myIconThemeDataAppBar,
          elevation: Constants.myElevationAppBar,
          backgroundColor: Constants.myAppBarColor,
        ),
        body: SingleChildScrollView(
            child: Column(children: <Widget>[
          Card(
              child: CalendarCarousel(
            weekendTextStyle: TextStyle(
              color: Colors.red,
            ),
            weekFormat: false,
            selectedDateTime: _currentDate,
            markedDatesMap: _markedDateMap,
            selectedDayBorderColor: Colors.transparent,
            selectedDayButtonColor: Colors.indigo[300],
            todayTextStyle:
                TextStyle(color: Colors.black, fontWeight: FontWeight.bold),
            selectedDayTextStyle: TextStyle(color: _colorTextButtonColor),
            todayBorderColor: Colors.indigo,
            weekdayTextStyle: TextStyle(color: Colors.black),
            height: 420.0,
            daysHaveCircularBorder: true,
            todayButtonColor: Colors.transparent,
            locale: 'RUS',
            onDayPressed: (DateTime date, List<Event> events) {
              this.setState(() => refresh(date));
            },
          )),
          Card(
              child: Container(
                  child: Padding(
                      padding: EdgeInsets.fromLTRB(16.0, 16.0, 16.0, 16.0),
                      child: Center(
                          child: Text(
                        calendarText,
                        style: Constants.textStyleCommonText,
                      )))))
        ])));
  }

  void refresh(DateTime date) {
    _currentDate = date;
    print('selected date ' +
        date.day.toString() +
        date.month.toString() +
        date.year.toString() +
        ' ' +
        date.toString());
    if (_markedDateMap
        .getEvents(new DateTime(date.year, date.month, date.day))
        .isNotEmpty) {
      calendarText = _markedDateMap
          .getEvents(new DateTime(date.year, date.month, date.day))[0]
          .title;
    } else {
      calendarText = noEventText;
    }
    if (date == _currentDate) {
      _colorButtonColor = Colors.indigo;
      _colorTextButtonColor = Colors.white;
      _colorTextTodayButton = Colors.white;
    } else {
      _colorTextButtonColor = Colors.indigo;
      _colorTextTodayButton = Colors.black;
    }
  }
}

EventList<Event> _markedDateMap = new EventList<Event>(events: {
  new DateTime(2019, 1, 24): [
    new Event(
      date: new DateTime(2019, 1, 24),
      title: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, '
          'sed eiusmod tempor incidunt ut labore et dolore magna aliqua.'
          ' \n\nUt enim ad minim veniam,'
          ' quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat.'
          ' \n\nQuis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. '
          'Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.',
      icon: _eventIcon,
    )
  ]
});

Widget _eventIcon = new Container(
  decoration: new BoxDecoration(
      color: Colors.white,
      borderRadius: BorderRadius.all(Radius.circular(1000)),
      border: Border.all(color: Colors.blue, width: 2.0)),
  child: new Icon(
    Icons.person,
    color: Colors.amber,
  ),
);
  Future<void> getCalendarEventList() async {
    await Firestore.instance.collection(_calendarRussian).snapshots().listen(
        (data) => data.documents.forEach((doc) => _markedDateMap.add(
            new DateTime(int.parse(doc[_eventYear]),
                int.parse(doc[_eventMonth]), int.parse(doc[_eventDay])),
            new Event(
                date: new DateTime(int.parse(doc[_eventYear]),
                    int.parse(doc[_eventMonth]), int.parse(doc[_eventDay])),
                title: doc[_eventTitle],
                icon: _eventIcon))));
    setState(() {});
  }
  @override
  void dispose(){
    _markedDateMap.clear();
    super.dispose();
  }