Как обработать цвет кнопки при нажатии в карусели календаря во флаттере - PullRequest
0 голосов
/ 24 января 2019

Я использую календарную карусель Календарная карусель Виджет для трепетания. Я пытаюсь нажать на случайную дату в календаре и изменить цвет кнопки и сохранить этот цвет, но сейчас я не могу получить такое поведение. Это мой код:

import 'package:flutter/material.dart';
import 'package:father_home_flutter/model/constants.dart';
import 'package:flutter_calendar_carousel/classes/event.dart';
import 'package:flutter_calendar_carousel/classes/event_list.dart';
import 'package:flutter_calendar_carousel/flutter_calendar_carousel.dart'
    show CalendarCarousel;

class ScreenCalendar extends StatefulWidget {
  @override
  _ScreenCalendarState createState() => new _ScreenCalendarState();
}

class _ScreenCalendarState extends State<ScreenCalendar> {
  static String noEventText = "No event here";
  String calendarText = noEventText;

  @override
  void initState() {
    _markedDateMap.add(
        new DateTime(2019, 1, 25),
        new Event(
          date: new DateTime(2019, 1, 25),
          title: 'Event 5',
          icon: _eventIcon,
        ));

    _markedDateMap.add(
        new DateTime(2019, 1, 10),
        new Event(
          date: new DateTime(2019, 1, 10),
          title: 'Event 4',
          icon: _eventIcon,
        ));

    _markedDateMap.addAll(new DateTime(2019, 1, 11), [
      new Event(
        date: new DateTime(2019, 1, 11),
        title: 'Event 1',
        icon: _eventIcon,
      ),
      new Event(
        date: new DateTime(2019, 1, 11),
        title: 'Event 2',
        icon: _eventIcon,
      ),
      new Event(
        date: new DateTime(2019, 1, 11),
        title: 'Event 3',
        icon: _eventIcon,
      ),
    ]);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(
            'Календар',
            style: Constants.myTextStyleAppBar,
          ),
          iconTheme: Constants.myIconThemeDataAppBar,
          elevation: Constants.myElevationAppBar,
          backgroundColor: Constants.myAppBarColor,
        ),
        body: SingleChildScrollView(
            child: Column(children: <Widget>[
          Card(
              child: CalendarCarousel(
            weekendTextStyle: TextStyle(
              color: Colors.red,
            ),
            weekFormat: false,
            selectedDayBorderColor: Colors.green,
            markedDatesMap: _markedDateMap,
            selectedDayButtonColor: Colors.green,
            selectedDayTextStyle: TextStyle(color: Colors.green),
            todayBorderColor: Colors.transparent,
            weekdayTextStyle: TextStyle(color: Colors.black),
            height: 420.0,
            daysHaveCircularBorder: true,
            todayButtonColor: Colors.indigo,
            locale: 'RUS',
            onDayPressed: (DateTime date, List<Event> events) {
              this.setState(() => refresh(date));
            },
          )),
          Card(
              child: Container(
                  child: Padding(
                      padding: EdgeInsets.fromLTRB(16.0, 16.0, 16.0, 16.0),
                      child: Center(
                          child: Text(
                        calendarText,
                        style: Constants.textStyleCommonText,
                      )))))
        ])));
  }

  void refresh(DateTime date) {
    print('selected date ' +
        date.day.toString() +
        date.month.toString() +
        date.year.toString() +
        ' ' +
        date.toString());
    if(_markedDateMap.getEvents(new DateTime(date.year, date.month, date.day)).isNotEmpty){
      calendarText = _markedDateMap
          .getEvents(new DateTime(date.year, date.month, date.day))[0]
          .title;
    } else{
      calendarText = noEventText;
    }
    }
  }

  EventList<Event> _markedDateMap = new EventList<Event>(events: {
    new DateTime(2019, 1, 24): [
      new Event(
        date: new DateTime(2019, 1, 24),
        title: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, '
            'sed eiusmod tempor incidunt ut labore et dolore magna aliqua.'
            ' \n\nUt enim ad minim veniam,'
            ' quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat.'
            ' \n\nQuis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. '
            'Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.',
        icon: _eventIcon,
      )
    ]
  });

   Widget _eventIcon = new Container(
    decoration: new BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(1000)),
        border: Border.all(color: Colors.blue, width: 2.0)),
    child: new Icon(
      Icons.person,
      color: Colors.amber,
    ),
  );

и текущее поведение:

enter image description here

Использование этих параметров не работает, как я ищу:

 selectedDayBorderColor: Colors.green,
 selectedDayButtonColor: Colors.green,
 selectedDayTextStyle: TextStyle(color: Colors.green),

Ответы [ 2 ]

0 голосов
/ 24 января 2019

Чтобы решить эту проблему, я сделал так, как предложил @miguelpruivo, исправив onDayPressed следующим образом:

 onDayPressed: (DateTime date, List<Event> events) {
              this.setState(() => refresh(date));
            },

void refresh(DateTime date) {
    _currentDate = date;

также в параметрах CalendarCarousel:

selectedDateTime: _currentDate,

и ниже объявления _ScreenCalendarState:

  DateTime _currentDate = DateTime.now();
0 голосов
/ 24 января 2019

Если вы пытаетесь изменить цвет заставки, вам может потребоваться переопределить его из текущей темы, попробуйте обернуть ваш виджет карусели календаря в Theme и переопределить ThemeData следующим образом:

 Theme(data: ThemeData(
      splashColor: Colors.green,
    )
    child: YourCarouselWidget(),
);

Также убедитесь, что вы обновляете выбранный день, указав setState в свойстве onDayPressed.

...