嘿,我正在一个项目中,在其中我使用table_calender创建事件并将其保存在数据库中,我已经成功地将其添加到数据库中,当只有一个事件发生时,当我必须检索它们时就会出现问题。在数据库中,它会根据日历显示一个制造商的日历日期,但是当有多个重复的日期时,它应该在该日期再次添加另一个标记,但它给出了例外,就是说当地图中的键为null时我在同一日期添加了另一个标记。 例外在 _events [mee.dateTime] .add(meetingInfo [i] ['m_agenda']);
for(int i=0; i<meetingInfo.length;i++)
{
if (_events[mee.dateTime] != null)
{
dateWithT=meetingInfo[i]['m_date'].replaceAll(new RegExp(r'[^\w\s]+'),'');
dateWithT=dateWithT.replaceAll(' ', '');
dateWithT=dateWithT+"000000";
dateWithT = dateWithT.substring(0, 8) + 'T' + dateWithT.substring(8);
mee.dateTime = DateTime.parse(dateWithT);
_events[mee.dateTime].add(meetingInfo[i]['m_agenda']);
}
else
{
dateWithT=meetingInfo[i]['m_date'].replaceAll(new RegExp(r'[^\w\s]+'),'');
dateWithT=dateWithT.replaceAll(' ', '');
dateWithT=dateWithT+"000000";
dateWithT = dateWithT.substring(0, 8) + 'T' + dateWithT.substring(8);
mee.dateTime = DateTime.parse(dateWithT);
_events[mee.dateTime] = [meetingInfo[i]['m_agenda']];
}
}
meeting.dart
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:intl/intl.dart';
import 'notifcation_dialog.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:table_calendar/table_calendar.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'variables.dart';
meeting mee = new meeting();
class AddMeeting extends StatefulWidget {
@override
_AddMeetingeState createState() => _AddMeetingeState();
}
class _AddMeetingeState extends State<AddMeeting> {
List meetDate;
CalendarController _controller;
Map<DateTime, List<dynamic>> _events;
List<dynamic> _selectedEvents;
TextEditingController _eventController;
// SharedPreferences prefs;
@override
void initState() {
super.initState();
_controller = CalendarController();
_eventController = TextEditingController();
_events = {};
_selectedEvents = [];
getIdAndGetMeetings();
}
String dateWithT;
String emailFromSharedPref, meetingAdded;
Map smData;
List meetingInfo, customerInfo;
Future getIdAndGetMeetings() async {
// getting email from SharedPreferences
SharedPreferences prefs = await SharedPreferences.getInstance();
emailFromSharedPref = prefs.getString('email');
// getting saleManager info using email
var url = "http://..../getSaleMangerDetal.php";
var response = await http.post(url, body: {
"m_email": emailFromSharedPref,
});
smData = jsonDecode(response.body);
// getting customer info using saleManagerID
var customerInfoUrl = "http://..../calender/getCustomerInfo.php";
var customerInfoResponse = await http.post(customerInfoUrl, body: {
"sm_id": smData['manager_id'],
});
// saving customer info in the list, because there are many dict in the list
customerInfo = jsonDecode(customerInfoResponse.body);
// get meetings details from server using saleManager Id
var getmeetingUrl = "http://..../getMeetings.php";
var getMeetiongResponse = await http.post(getmeetingUrl, body: {
"manager_id": smData['manager_id'],
});
meetingInfo = jsonDecode(getMeetiongResponse.body);
print(meetingInfo);
for(int i=0; i<meetingInfo.length;i++)
{
if (_events[mee.dateTime] != null)
{
dateWithT=meetingInfo[i]['m_date'].replaceAll(new RegExp(r'[^\w\s]+'),'');
dateWithT=dateWithT.replaceAll(' ', '');
dateWithT=dateWithT+"000000";
dateWithT = dateWithT.substring(0, 8) + 'T' + dateWithT.substring(8);
mee.dateTime = DateTime.parse(dateWithT);
_events[mee.dateTime].add(meetingInfo[i]['m_agenda']);
}
else
{
dateWithT=meetingInfo[i]['m_date'].replaceAll(new RegExp(r'[^\w\s]+'),'');
dateWithT=dateWithT.replaceAll(' ', '');
dateWithT=dateWithT+"000000";
dateWithT = dateWithT.substring(0, 8) + 'T' + dateWithT.substring(8);
mee.dateTime = DateTime.parse(dateWithT);
_events[mee.dateTime] = [meetingInfo[i]['m_agenda']];
}
}
}
Map<String, dynamic> encodeMap(Map<DateTime, dynamic> map) {
Map<String, dynamic> newMap = {};
map.forEach((key, value) {
newMap[key.toString()] = map[key];
});
return newMap;
}
Map<DateTime, dynamic> decodeMap(Map<String, dynamic> map) {
Map<DateTime, dynamic> newMap = {};
map.forEach((key, value) {
newMap[DateTime.parse(key)] = map[key];
});
return newMap;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Calendar'),
),
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
TableCalendar(
events: _events,
// initialCalendarFormat: CalendarFormat.week,
calendarStyle: CalendarStyle(
canEventMarkersOverflow: true,
todayColor: Colors.orange,
selectedColor: Theme.of(context).primaryColor,
todayStyle: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18.0,
color: Colors.white)),
headerStyle: HeaderStyle(
centerHeaderTitle: true,
formatButtonDecoration: BoxDecoration(
color: Colors.orange,
borderRadius: BorderRadius.circular(20.0),
),
formatButtonTextStyle: TextStyle(color: Colors.white),
formatButtonShowsNext: false,
),
startingDayOfWeek: StartingDayOfWeek.monday,
onDaySelected: (date, events) {
setState(() {
_selectedEvents = events;
});
},
builders: CalendarBuilders(
selectedDayBuilder: (context, date, events) => Container(
margin: const EdgeInsets.all(4.0),
alignment: Alignment.center,
decoration: BoxDecoration(
color: Theme.of(context).primaryColor,
borderRadius: BorderRadius.circular(10.0)),
child: Text(
date.day.toString(),
style: TextStyle(color: Colors.white),
)),
todayDayBuilder: (context, date, events) => Container(
margin: const EdgeInsets.all(4.0),
alignment: Alignment.center,
decoration: BoxDecoration(
color: Colors.orange,
borderRadius: BorderRadius.circular(10.0)),
child: Text(
date.day.toString(),
style: TextStyle(color: Colors.white),
)),
),
calendarController: _controller,
),
..._selectedEvents.map((event) => ListTile(
title: Text(event),
)),
],
),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: _showAddDialog,
),
);
}
_showAddDialog() async {
await showDialog(
context: context,
builder: (context) => AlertDialog(
content: TextField(
controller: _eventController,
),
actions: <Widget>[
FlatButton(
child: Text("Save"),
onPressed: ()
{
// if (_eventController.text.isEmpty) return;
// if (_events[_controller.selectedDay] != null) {
// _events[_controller.selectedDay]
// .add(_eventController.text);
String asd = _controller.selectedDay.toString();
meetDate = asd.split(' ');
addMeetingToDatabase(meetDate);
// }
// else
// {
// // _events[_controller.selectedDay] = [
// // _eventController.text
// // ];
// String asd = _controller.selectedDay.toString();
// meetDate = asd.split(' ');
// addMeetingToDatabase(meetDate);
// // print(_controller.selectedDay);
// }
// prefs.setString("events", json.encode(encodeMap(_events)));
_eventController.clear();
Navigator.pop(context);
},
)
],
));
setState(() {
_selectedEvents = _events[mee.dateTime];
});
}
addMeetingToDatabase(List meetDate2) async {
// print(meetDate2[0]);
var getmeetingUrls = "http://..../addMeeting.php";
var getMeetiongResponses = await http.post(getmeetingUrls, body: {
"sm_id": smData['manager_id'],
"c_id": '2',
"agenda": _eventController.text,
"date": meetDate2[0],
// "time":smData['manager_id'],
});
meetingAdded = jsonDecode(getMeetiongResponses.body);
print(meetingAdded);
}
}
答案 0 :(得分:2)
似乎您正在尝试在Map
中不存在的对象上调用方法。
mee.dateTime = DateTime.parse(dateWithT);
_events[mee.dateTime].add(meetingInfo[i]['m_agenda']);
在上面的代码中,如果地图中没有mee.dateTime
,它将返回null
,这当前是导致您异常的原因。
现在,您有支票
if (_events[mee.dateTime] != null) {
...
mee.dateTime = DateTime.parse(dateWithT);
_events[mee.dateTime].add(meetingInfo[i]['m_agenda']);
}
因此,基本上,dateTime
(在您进入本节之前在地图中找到的位置)现在在块内进行了更新。现在,您无需检查地图中是否存在新的dateTime。
您的代码中存在逻辑问题。