首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Flutter table_calendar -在null上调用了getter 'month‘

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

Stack Overflow用户
提问于 2021-01-21 11:54:21
回答 1查看 147关注 0票数 0

作为第一个主要项目,我还是个新手。我遇到一个getter month被调用时出现null错误。

代码语言:javascript
运行
复制
 ══╡ 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)

我找不到问题所在。以下是页面中的代码。任何帮助都将不胜感激。

代码语言:javascript
运行
复制
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()),
                    ],
                  ),
                ),
        );
      },
    );
  }
}
EN

回答 1

Stack Overflow用户

发布于 2021-01-23 10:50:53

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

代码语言:javascript
运行
复制
_calendarController = CalendarController();

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65820949

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档