Ошибка флаттера NoSuchMethodError: метод 'map' был вызван с нулевым значением. Получатель: null Пробный вызов: карта (Закрытие: (Dynami c) => Контейнер) - PullRequest
0 голосов
/ 30 апреля 2020

Привет, у меня проблемы со страницей календаря, и я не могу понять, почему у меня ошибка. любая помощь будет принята с благодарностью. Большое спасибо

Ошибка, которую я получаю: NoSuchMethodError: метод 'map' был вызван для нуля. Получатель: null Пробный вызов: карта (Закрытие: (Dynami c) => Контейнер) См. Также: flutter.dev/docs/tersting/errors

вот мой код для страницы:

   import ‘package:flutter/cupertino.dart’;
import ‘package:flutter/material.dart’;
import ‘dart:convert’;
//import ‘package:intl/date_symbol_data_local.dart’;
import ‘package:global_configuration/global_configuration.dart’;
import ‘package:get/get.dart’;
import ‘package:http/http.dart’ as http;
import ‘package:flutter/scheduler.dart’;
import ‘package:has_answers/commons/sidebar.dart’;
import ‘package:shared_preferences/shared_preferences.dart’;
import ‘package:table_calendar/table_calendar.dart’;

final _baseURL = GlobalConfiguration().getString(“BaseURL”);

class UserCalendarPage extends StatefulWidget {
@override
_UserCalendarPageState createState() => new _UserCalendarPageState();
}

class _UserCalendarPageState extends State
with TickerProviderStateMixin {
CalendarController _calendarController;
DateTime daySelected;
Map<DateTime, List> _events;
List _selectedEvents;
AnimationController _animationController;
List _eventList = [];
List _dates;
final _selectedDay = DateTime.now();
SharedPreferences sharedPreferences;
String fullname;
bool isloggedIn;
String userid;
String userName = ‘’;
String passWord = ‘’;
String authtoken;

void loadSharedPrefs() async {
SharedPreferences.getInstance().then((SharedPreferences sp) {
sharedPreferences = sp;
fullname = sharedPreferences.getString(“fullname”);
userid = sharedPreferences.getString(“userid”);
authtoken = sharedPreferences.getString(“authtoken”);
isloggedIn = sharedPreferences.getBool(“isloggedin”);
// will be null if never previously saved
if (fullname == null) {
isloggedIn = false;
fullname = “”;
persist(
fullname, userid, isloggedIn, authtoken); // set an initial value
}
setState(() {});
});
}
void persist(String value, String userid, bool loginValue, String authtoken) {
setState(() {
isloggedIn = loginValue;
fullname = value;
authtoken = authtoken;
userid = userid;
});
sharedPreferences?.setString(“fullname”, value);
sharedPreferences?.setString(“userid”, userid);
sharedPreferences?.setBool(“isloggedin”, loginValue);
sharedPreferences?.setString(“authtoken”, authtoken);
}

@override
void initState() {
loadSharedPrefs();
if (isloggedIn == false) {
SchedulerBinding.instance.addPostFrameCallback((_) {
Get.toNamed("/Login");
// Navigator.of(context).pushNamed(“login”);
});
}
super.initState();
this.daySelected = DateTime.now();
_fetchList();

_calendarController = CalendarController();
//final _selectedDay = DateTime.now();
//COMMENTED OUT EVENTS(see bottom of page)

_animationController = AnimationController(
 vsync: this,
 duration: const Duration(milliseconds: 400),
);
_animationController.forward();
}

Future _fetchList() async {
_eventList = await fetchEvents(‘2020-10’);
// below is processing the of _eventList so events are mapped according the date
// for(EventModel e in _eventList){
// _dates.add(e.eventdate);
// }
_dates.toSet().toList();
Map<DateTime, List> eventsParsed = {};
for (var i = 0; i < _dates.length; i++) {
List singleDayEvents =
_eventList.where((e) => e.eventdate.contains(_dates[i])).toList();
eventsParsed[DateTime.parse(_dates[i])] = singleDayEvents;
}
_events = eventsParsed;
_selectedEvents = _events[_selectedDay] ?? [];
}

@override
void dispose() {
_animationController.dispose();
_calendarController.dispose();
super.dispose();
}

void _onDaySelected(DateTime day, List events) {
print(‘CALLBACK: _onDaySelected’);
setState(() {
_selectedEvents = events;
});
}

void _onVisibleDaysChanged(
DateTime first, DateTime last, CalendarFormat format) {
print(‘CALLBACK: _onVisibleDaysChanged’);
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(‘Your Calendar’),
),
drawer: HasSideBarDrawer(),
body: Column(
mainAxisSize: MainAxisSize.max,
children: [
_buildCalendar(),
const SizedBox(height: 8.0),
// _buildButtons(),
const SizedBox(height: 8.0),
Expanded(child: _buildEventList()),
],
),
);
}

Widget _buildCalendar() {
return TableCalendar(
locale: ‘en_GB’,
calendarController: _calendarController,
events: _events,
initialCalendarFormat: CalendarFormat.month,
formatAnimation: FormatAnimation.slide,
startingDayOfWeek: StartingDayOfWeek.sunday,
availableGestures: AvailableGestures.all,
availableCalendarFormats: const {
CalendarFormat.month: ‘’,
CalendarFormat.week: ‘’,
},
calendarStyle: CalendarStyle(
outsideDaysVisible: false,
weekendStyle: TextStyle().copyWith(color: Colors.blue[800]),
holidayStyle: TextStyle().copyWith(color: Colors.blue[800]),
),
daysOfWeekStyle: DaysOfWeekStyle(
weekendStyle: TextStyle().copyWith(color: Colors.blue[600]),
),
headerStyle: HeaderStyle(
centerHeaderTitle: true,
formatButtonVisible: false,
),
builders: CalendarBuilders(
selectedDayBuilder: (context, date, _) {
return FadeTransition(
opacity: Tween(begin: 0.0, end: 1.0).animate(_animationController),
child: Container(
margin: const EdgeInsets.all(4.0),
padding: const EdgeInsets.only(top: 5.0, left: 6.0),
color: Colors.deepOrange[300],
width: 100,
height: 100,
child: Text(
‘${date.day}’,
style: TextStyle().copyWith(fontSize: 16.0),
),
),
);
},
todayDayBuilder: (context, date, _) {
return Container(
margin: const EdgeInsets.all(4.0),
padding: const EdgeInsets.only(top: 5.0, left: 6.0),
color: Colors.amber[400],
width: 100,
height: 100,
child: Text(
‘${date.day}’,
style: TextStyle().copyWith(fontSize: 16.0),
),
);
},
markersBuilder: (context, date, events, holidays) {
final children = [];

     if (events.isNotEmpty) {
       children.add(
         Positioned(
           right: 1,
           bottom: 1,
           child: _buildEventsMarker(date, events),
         ),
       );
     }

     if (holidays.isNotEmpty) {
       children.add(
         Positioned(
           right: -2,
           top: -2,
           child: _buildHolidaysMarker(),
         ),
       );
     }

     return children;
   },
 ),
 onDaySelected: (date, events) {
   _onDaySelected(date, events);
   _animationController.forward(from: 0.0);
 },
 onVisibleDaysChanged: _onVisibleDaysChanged,
);
}

Widget _buildEventsMarker(DateTime date, List events) {
return AnimatedContainer(
duration: const Duration(milliseconds: 300),
decoration: BoxDecoration(
shape: BoxShape.rectangle,
color: _calendarController.isSelected(date)
? Colors.brown[500]
: _calendarController.isToday(date)
? Colors.brown[300]
: Colors.blue[400],
),
width: 16.0,
height: 16.0,
child: Center(
child: Text(
‘${events.length}’,
style: TextStyle().copyWith(
color: Colors.white,
fontSize: 12.0,
),
),
),
);
}

Widget _buildHolidaysMarker() {
return Icon(
Icons.add_box,
size: 20.0,
color: Colors.blueGrey[800],
);
}

Widget _buildEventList() {
return ListView(
children: _selectedEvents
.map((event) => Container(
decoration: BoxDecoration(
border: Border.all(width: 0.8),
borderRadius: BorderRadius.circular(12.0),
),
margin:
const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
child: ListTile(
title: Text(event.toString()),
onTap: () => print(’$event tapped!’),
),
))
.toList(),
);
}

Future<List> fetchEvents(String month) async {
String url = _baseURL + “MY URL.php”;
Map<String, dynamic> body = {
‘authtoken’: authtoken,
‘uid’: userid,
‘month’: month
};

List events = [];
await http.post(url, body: body).then((http.Response response) {

final int statusCode = response.statusCode;

if (statusCode == 200) {
 if (response.body ==
     '{"message":"Something went wrong, please contact IT Support. error code:2"}') {
   return throw Exception('Error');
 } else {
   //Send Data to post to format.
   var jsonData = json.decode(response.body);
   for (var e in jsonData) {
     EventModel event = EventModel(
         eventid: e["id"],
         eventdate: e["eventdate"],
         eventname: e["title"],
         eventdescription: e['description']);

     events.add(event);
   }
 }
}
print('Total Events= ' + events.length.toString());
});
return events;
}

} //END CLASS

class EventModel {
final int eventid;
final String eventdate;
final String eventname;
final String eventdescription;

EventModel(
{this.eventid, this.eventdate, this.eventname, this.eventdescription});
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...