Flutter table_calendar - 在 null 上调用了 getter 'month'

时间:2021-01-21 03:54:20

标签: flutter

我还是很陌生,因为这是第一个重大项目。我遇到了一个 getter 月份,在 null 错误时被调用。

 ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (12062): The following NoSuchMethodError was thrown building TableCalendar(dirty, state:
I/flutter (12062): _TableCalendarState#79f31(ticker inactive)):
I/flutter (12062): The getter 'month' was called on null.
I/flutter (12062): Receiver: null
I/flutter (12062): Tried calling: month
I/flutter (12062): 
I/flutter (12062): The relevant error-causing widget was:
I/flutter (12062):   TableCalendar
I/flutter (12062):   file:///Users/cwesterhold/FlutterApps/pivoti/lib/screens/calendar/calendarMain.dart:52:14
I/flutter (12062): 
I/flutter (12062): When the exception was thrown, this was the stack:
I/flutter (12062): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
I/flutter (12062): #1      _DateFormatPatternField.formatMonth (package:intl/src/intl/date_format_field.dart:451:36)
I/flutter (12062): #2      _DateFormatPatternField.formatField (package:intl/src/intl/date_format_field.dart:367:16)
I/flutter (12062): #3      _DateFormatPatternField.format (package:intl/src/intl/date_format_field.dart:244:12)
I/flutter (12062): #4      DateFormat.format (package:intl/src/intl/date_format.dart:276:26)

日历初始加载正常工作,同时向前或向后更改月份。选择单独的日期时出现问题 (_onDaySelected)

我找不到似乎找到了问题。这是页面上的代码。任何帮助将不胜感激。

import 'package:dart_date/dart_date.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pivoti/bloc/calendar/calendar.dart';
import 'package:pivoti/services/hexcolor.dart';
import 'package:table_calendar/table_calendar.dart';

class CalendarScreen extends StatefulWidget {
  @override
  _CalendarScreenState createState() => _CalendarScreenState();
}

class _CalendarScreenState extends State<CalendarScreen> with TickerProviderStateMixin {
  bool _loading = true;
  Map<DateTime, List> _events;
  List _selectedEvents;
  AnimationController _animationController;
  CalendarController _calendarController;

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

  @override
  Widget build(BuildContext context) {
    CalendarBloc _calendarBloc = BlocProvider.of<CalendarBloc>(context);

    _calendarController = CalendarController();

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

    void _onDaySelected(DateTime day, List events, List holidays) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        setState(() {
          _selectedEvents = events;
          _animationController.forward(from: 0.0);
        });
      });
    }

    void _onVisibleDaysChanged(DateTime first, DateTime last, CalendarFormat format) {
      _calendarBloc.add(FetchEvents(first, last));
    }

    Widget _buildTableCalendar() {
      return TableCalendar(
        calendarController: _calendarController,
        events: _events,
        startingDayOfWeek: StartingDayOfWeek.sunday,
        availableCalendarFormats: const {
          CalendarFormat.month: 'Week',
          CalendarFormat.week: 'Month',
        },
        availableGestures: AvailableGestures.all,
        formatAnimation: FormatAnimation.slide,
        calendarStyle: CalendarStyle(
          selectedColor: HexColor('#FF7518'),
          todayColor: Colors.deepOrange[200],
          markersColor: HexColor('#137DC5'),
          outsideDaysVisible: false,
        ),
        headerStyle: HeaderStyle(
          formatButtonTextStyle: TextStyle().copyWith(color: Colors.white, fontSize: 15.0),
          formatButtonDecoration: BoxDecoration(
            color: HexColor('#FF7518'),
            borderRadius: BorderRadius.circular(16.0),
          ),
        ),
        onDaySelected: _onDaySelected,
        onVisibleDaysChanged: _onVisibleDaysChanged,
      );
    }

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

    return BlocBuilder<CalendarBloc, CalendarState>(
      builder: (context, state) {
        print(state);
        if (state is IsStart || (state is IsNormal && _loading == true)) {
          final firstDayOfMonth = DateTime.now().startOfMonth;
          final lastDayOfMonth = DateTime.now().endOfMonth;

          _calendarBloc.add(FetchEvents(firstDayOfMonth, lastDayOfMonth));
        } else if (state is EventsFetched) {
          final _selectedDay = DateTime.parse(DateTime.now().format('yyyy-MM-DD'));

          _events = {
            for (var v in state.events) DateTime.parse(v.fullDate.format('yyyy-MM-DD')): v.events
          };

          _selectedEvents = _events[_selectedDay] ?? [];

          _loading = false;
          _animationController.forward();
          _calendarBloc.add(Normal());
        }

        return Scaffold(
          body: _loading
              ? Center(
                  child: CircularProgressIndicator(
                    valueColor: AlwaysStoppedAnimation<Color>(Theme.of(context).accentColor),
                  ),
                )
              : SafeArea(
                  child: Column(
                    children: <Widget>[
                      _buildTableCalendar(),
                      const SizedBox(height: 8.0),
                      Expanded(child: _buildEventList()),
                    ],
                  ),
                ),
        );
      },
    );
  }
}

1 个答案:

答案 0 :(得分:0)

经过一些挖掘和 table_calendar 创建者的回应。问题是

_calendarController = CalendarController();

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

在 build() 中而不是在 initState() 中。