Flutter 问题:类型 'Null' 不是 'DateTime' 的子类型

Flutter issue : type 'Null' is not a subtype of 'DateTime'

我正在寻求有关个人项目的帮助。基本上,我将日历作为应用程序抽屉选项,当我还在日历页面和热重新加载时它正在工作,但现在在热重启后它一直向我显示此错误

type 'Null' is not a subtype of type 'DateTime'

这是我的日历屏幕代码:

import 'package:attendance_checker/screens/home.dart';

import 'package:flutter/material.dart';
import 'package:table_calendar/table_calendar.dart';
import 'package:attendance_checker/models/calendar_events.dart';

class Calender extends StatefulWidget {
  const Calender({Key? key}) : super(key: key);

  @override
  _CalenderState createState() => _CalenderState();
}

class _CalenderState extends State<Calender> {
  late Map<DateTime, List<Event>> selectedEvents;
  CalendarFormat format = CalendarFormat.month;
  var focusedDay;
  var selectedDay;

  TextEditingController _eventController = TextEditingController();

  @override
  void initState() {
    selectedEvents = {};
    super.initState();
  }

  @override
  void dispose() {
    _eventController.dispose();
    super.dispose();
  }

  List<Event> _getEventsfromDay(DateTime date) {
    return selectedEvents[date] ?? [];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: BackButton(
            color: Colors.white,
            onPressed: () => Navigator.pushReplacement(
                context, MaterialPageRoute(builder: (context) => Home()))),
        title: Text("Calendar"),
        backgroundColor: Colors.green[700],
      ),
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            Column(
              children: [
                TableCalendar(
                  focusedDay: DateTime.now(),
                  firstDay: DateTime.utc(2010, 10, 16),
                  lastDay: DateTime.utc(2030, 3, 14),
                  calendarFormat: format,
                  onFormatChanged: (CalendarFormat _format) {
                    setState(() {
                      format = _format;
                    });
                  },
                  eventLoader: _getEventsfromDay,
                  calendarStyle: CalendarStyle(
                      isTodayHighlighted: true,
                      selectedDecoration: BoxDecoration(
                        color: Colors.green[300],
                        shape: BoxShape.circle,
                      ),
                      selectedTextStyle: TextStyle(color: Colors.white),
                      todayDecoration: BoxDecoration(
                        color: Colors.green[700],
                        shape: BoxShape.circle,
                      )),
                  startingDayOfWeek: StartingDayOfWeek.sunday,
                  daysOfWeekVisible: true,
                  onDaySelected: (DateTime selectDay, DateTime focusDay) {
                    setState(() {
                      selectedDay = selectDay;
                      focusedDay = focusDay;
                    });
                    print(focusedDay);
                  },
                  selectedDayPredicate: (DateTime date) {
                    return isSameDay(selectedDay, date);
                  },
                  headerStyle: HeaderStyle(
                      formatButtonVisible: false, titleCentered: true),
                ),
                ..._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(
                  onPressed: () => Navigator.pop(context),
                  child: Text("Cancel")),
              TextButton(
                  onPressed: () {
                    if (_eventController.text.isEmpty) {
                    } else {
                      if (selectedEvents[selectedDay] != null) {
                        selectedEvents[selectedDay]!
                            .add(Event(title: _eventController.text));
                      } else {
                        selectedEvents[selectedDay] = [
                          Event(title: _eventController.text)
                        ];
                      }
                    }
                    Navigator.pop(context);
                    _eventController.clear();
                    setState(() {});
                    return;
                  },
                  child: Text("OK"))
            ],
          ),
        ),
        label: Text("Add label"),
        icon: Icon(Icons.add),
        backgroundColor: Colors.green[600],
      ),
    );
  }
}

这里是我调用日历屏幕的地方:

import 'package:attendance_checker/screens/calender.dart';
import 'package:attendance_checker/screens/help.dart';
import 'package:attendance_checker/widgets/checkboxlist.dart';
import 'package:attendance_checker/widgets/classinfo.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class Home extends StatefulWidget {
  //const Home({ key }) : super(key: key);

  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Attendance Checker"),
          backgroundColor: Colors.green[700],
        ),
        drawer: Drawer(
          child: ListView(
            children: [
              DrawerHeader(
                child: Text(
                  "Drawer header",
                  style: TextStyle(fontSize: 24, color: Colors.white),
                ),
                decoration: BoxDecoration(color: Colors.green[700]),
              ),
              ListTile(
                title: Text("Calender"),
                trailing: Icon(Icons.calendar_today_rounded),
                onTap: () {
                  Navigator.pushReplacement(context,
                      MaterialPageRoute(builder: (context) => Calender()));
                },
              ),
              ListTile(
                title: Text("Help"),
                trailing: Icon(Icons.question_answer),
                onTap: () {
                  Navigator.pushReplacement(
                      context, MaterialPageRoute(builder: (context) => Help()));
                },
              )
            ],
          ),
        ),
        backgroundColor: Colors.green[400],
        body: Column(
          children: <Widget>[ClassInfo(), Checklist()],
        ));
  }
}

我不确定为什么会出现这个错误,但如果你能帮助我解决这个问题,那将是很大的帮助。提前致谢

如果将 var selectedDate 行更改为下面的行,它是否有效

 late DateTime selectedDay;

然后进行如下所示的修改:

  • 添加 toList.map() 方法 returns 和 Iterable,您必须将其转换为 List 才能使用它作为 Column)
  • children
  • 添加 if 检查以确保 selectedDay 在您要使用它时已分配。
if (selectedDay != null)
                ..._getEventsfromDay(selectedDay).map((Event event) => ListTile(
                      title: Text(event.title),
                    )).toList(),