как получить события из API и показать его в событиях TableCalendar - PullRequest
0 голосов
/ 12 апреля 2020

как получать события из api и показывать их в событиях TableCalendar? Вот мой код и он не работает мои переменные

  Map<DateTime, List<Exam>> _events;
  CalendarController _calendarController;
  AnimationController _animationController;
  List<Exam> _selectedEvents=[];

мой inintstate и распоряжаться вызывать из API, но я не знаю, как это сделать метод, поэтому я возвратил данные stati c с function

  @override
  void initState() {
    super.initState();
    final _selectedDay = DateTime.now();
    getExamsAPI.getStaticExamApiEvents2().then((onValue){
      print('examsLoaded = $examsLoaded');
      setState(() {
       _events = onValue;
       print(_events);
       _selectedEvents = _events[_selectedDay] ?? [];
       examsLoaded = true;
      });
      print('examsLoaded = $examsLoaded');
    });
    _calendarController = CalendarController();

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

    _animationController.forward();

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

мой виджет календаря, и я не уверен, что он правильный, но это должно быть

  myCalendar() {
    return SizedBox(
      height: 0.5*MediaQuery.of(context).size.height,
      child: TableCalendar(
      calendarController: _calendarController,
      events: _events,
      startingDayOfWeek: StartingDayOfWeek.sunday,
      calendarStyle: CalendarStyle(
        selectedColor: Colors.green[700],
        todayColor: Colors.green[200],
        markersColor: Colors.brown[700],
        outsideDaysVisible: false,
      ),
      weekendDays: const [DateTime.friday,DateTime.saturday],
      headerStyle: HeaderStyle(
        formatButtonShowsNext: true,
        centerHeaderTitle: true,
        formatButtonTextStyle: TextStyle().copyWith(color: Colors.white, fontSize: 15.0),
        formatButtonDecoration: BoxDecoration(
          color: Colors.blue[400],
          borderRadius: BorderRadius.circular(16.0),
        ),
        formatButtonVisible: false,
      ),
      onDaySelected: _onDaySelected,

      onVisibleDaysChanged: _onVisibleDaysChanged,
      onCalendarCreated: _onCalendarCreated,
      builders: CalendarBuilders(
        markersBuilder: (context, date, events, holidays) {
          final children = <Widget>[];

          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;
        },
        selectedDayBuilder: (context,date,events) => Container(
          margin: EdgeInsets.all(4),
          alignment: Alignment.center,
          decoration: BoxDecoration(
              color: Colors.green[700],
              borderRadius: BorderRadius.all(Radius.circular(24),)
          ),
          child: Text(date.day.toString(),style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold),),
        ),
        todayDayBuilder: (context,date,events) => Container(
          margin: EdgeInsets.all(4),
          alignment: Alignment.center,
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(50),),
              border: Border.all(color: Colors.grey[200])
          ),
          child: Text(date.day.toString(),style: TextStyle(color: Colors.black,fontWeight: FontWeight.bold),),
        ),
      ),
    ),
    );
  }

в методах создания и выбора, пожалуйста, проверьте его еще раз

  void _onDaySelected(DateTime day, List events) {
    print('CALLBACK: _onDaySelected');
    print('_selectedEvents: $_selectedEvents');
    print('events: $events');

    setState(() {
      _selectedEvents = events;
    });
  }

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

  void _onCalendarCreated(DateTime first, DateTime last, CalendarFormat format) {
    print('CALLBACK: _onCalendarCreated');
  }

мой список событий для отображения событий на экране

  eventsList() {
    return SizedBox(
      height: 0.20*MediaQuery.of(context).size.height,
      child: ListView.builder(
        itemCount: _selectedEvents.length+1,
        itemBuilder:  (context, index) {
          return index == 0 ? Container() : SizedBox(
            height: 0.1*MediaQuery.of(context).size.height,
            child: FittedBox(
              child: oneExamEvent(_selectedEvents[index-1].title, '0xffbff144', ''),
            ),
          );
        },
      ),
    );
  }

oneExamEvent, возвращенный в список в функции списка

  oneExamEvent(title,color,date) {
    return Container(
      margin: new EdgeInsets.symmetric(vertical: 10.0),
      decoration: BoxDecoration(
        color: Color(int.parse(color)),
        borderRadius: BorderRadius.all(Radius.circular(8),),
      ),
      height: 0.14*MediaQuery.of(context).size.height,
      width: 0.9*MediaQuery.of(context).size.height,
      child: Row(
        children: <Widget>[
          SizedBox(
            width: 0.1*MediaQuery.of(context).size.width,
            height: 0.1*MediaQuery.of(context).size.width,
            child: FittedBox(
              child: Container(
                decoration: BoxDecoration(
                  shape: BoxShape.rectangle,
                  color: liteGreen,
                ),
                child: Padding(
                  padding: const EdgeInsets.all(4.0),
                  child: Image.asset(fileIconGrey,color: Colors.white,fit: BoxFit.scaleDown,),
                ),
              ),
            ),
          ),
          SizedBox(width: 0.02*MediaQuery.of(context).size.width,),
          SizedBox(
            width: 0.4*MediaQuery.of(context).size.width,
            child: FittedBox(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text('$title',style: TextStyle(fontFamily: 'Cairo',),),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...