我是flutter编程的新手,我按照本教程设置了表日历,以允许用户添加自己的事件。然而,当我转到应用程序的另一个页面或重新启动应用程序时,日历上的事件不会保存。有人知道如何确保事件不会消失吗?谢谢你!
代码:class CalendarRoute extends StatefulWidget{
@override
_CalendarRouteState createState() => _CalendarRouteState();
}
class _CalendarRouteState extends State<CalendarRoute> {
CalendarFormat format = CalendarFormat.month;
DateTime selectedDay = date;
DateTime focusedDay = date;
late Map <DateTime,List<Event>> selectedEvents;
TextEditingController _eventController = TextEditingController();
@override
void initState(){
selectedEvents = {};
super.initState();
}
List<Event> _getEventsFromDay(DateTime date){
return selectedEvents[date]??[];
}
void dispose(){
_eventController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Calendar",
style: TextStyle(color: Colors.yellow)),
backgroundColor: Colors.brown,
),
body:
Column(
children:[
TableCalendar(
firstDay: DateTime.utc(2021,6,8),
lastDay: DateTime.utc(2022,6,8),
focusedDay: focusedDay,
calendarFormat: format,
onFormatChanged: (CalendarFormat _format){
setState((){
format = _format;
});
},
startingDayOfWeek: StartingDayOfWeek.monday,
onDaySelected: (DateTime selectDay, DateTime focusDay){
setState((){
selectedDay = selectDay;
focusedDay = focusDay;
});
},
selectedDayPredicate: (DateTime day){
return isSameDay(selectedDay, day);
},
eventLoader:_getEventsFromDay,
calendarStyle: CalendarStyle(
isTodayHighlighted: true,
selectedDecoration: BoxDecoration(
color: Colors.yellow,
shape: BoxShape.rectangle,
),
selectedTextStyle: TextStyle(color: Colors.black),
todayDecoration: BoxDecoration(
color: Colors.brown,
shape: BoxShape.rectangle,
)
),
headerStyle:HeaderStyle(
formatButtonVisible: true,
titleCentered: true,
formatButtonShowsNext: false,
formatButtonDecoration: BoxDecoration(
color: Colors.brown,
),
formatButtonTextStyle: TextStyle(color: Colors.yellow)
)
),
..._getEventsFromDay(selectedDay).map((Event event)=> ListTile(title:Text(event.title))),
]),
floatingActionButton: FloatingActionButton.extended(
onPressed: ()=>showDialog(context:context, builder: (context)=>AlertDialog(
title: Text("Add event"),
content: TextFormField(
controller:_eventController,
),
actions: [TextButton(
child: Text("Cancel"),
onPressed:() =>Navigator.pop(context),
),
TextButton(
child: Text("Ok"),
onPressed:() {
if(_eventController.text.isEmpty){
}
else if (selectedEvents[selectedDay]!=null){
selectedEvents[selectedDay]!.add(
Event(title: _eventController.text),);
}
else{
selectedEvents[selectedDay] = [Event(
title: _eventController.text
)
];
}
_eventController.clear();
Navigator.pop(context);
setState((){});
return;
}
),]
)),
label: Text("Add event"),
icon: Icon(Icons.add),
),
您需要使用shared_preferences
链接到pub包
更多信息在这里在Flutter.dev