Kitereative Indonesia
Kitereative Indonesia

Reputation: 1217

flutter - make dynamic mark event in calendar plugin

I want to mark the event once every 4 days.

example today is the 1st, mark the event will be available on the 5th, 10th, 15th, 20th, 25th, 30th, etc.

if today is the 3rd, the event will be available on the 8th, 13th, 18th, etc.

how does that function work?

I use this calendar plugin

https://pub.dev/packages/flutter_calendar_carousel

Following is the function to mark event manually:

EventList<Event> _markedDateMap = new EventList<Event>();

   build(){
       _calendarCarouselNoHeader = CalendarCarousel<Event>(
       ...
       markedDatesMap: _markedDateMap,
       ...
       ),
    }

 @override
  void initState() {

     _markedDateMap.add(
         new DateTime(2020, 2, 26),
        new Event(
         date: new DateTime(2020, 2, 26),
         title: 'Event 5',
         icon: _eventIcon,
         ));

     _markedDateMap.add(
         new DateTime(2020, 2, 26),
        new Event(
         date: new DateTime(2020, 2, 26),
         title: 'Event 5',
         icon: _eventIcon,
         ));

    super.initState();
}

Any anwser will appreciated.

Upvotes: 1

Views: 4964

Answers (1)

chunhunghan
chunhunghan

Reputation: 54397

You can copy paste run full code below
working demo show when pass start date time with

addMarker(DateTime(2020, 2, 01));
addMarker(DateTime(2020, 2, 03));

code snippet

addMarker(DateTime startEventDateTime) {

    var eventDateTime = startEventDateTime;

    for(int i=0; i<5; i++) {
      if(eventDateTime.day == 1) {
        eventDateTime = eventDateTime.add(Duration(days: (4)));
      } else {
        eventDateTime = eventDateTime.add(Duration(days: (5)));
      }
      print(eventDateTime.toLocal());
      _markedDateMap.add(
          eventDateTime,
          Event(
            date: eventDateTime,
            title: 'Event $i',
            icon: _eventIcon,
          ));

    }
  }

working demo

enter image description here

full code

import 'package:flutter/material.dart';

import 'package:flutter_calendar_carousel/flutter_calendar_carousel.dart'
    show CalendarCarousel;
import 'package:flutter_calendar_carousel/classes/event.dart';
import 'package:flutter_calendar_carousel/classes/event_list.dart';
import 'package:intl/intl.dart' show DateFormat;

void main() => runApp( MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return  MaterialApp(
      title: 'dooboolab flutter calendar',
      theme:  ThemeData(
        primarySwatch: Colors.blue,
      ),
      home:  MyHomePage(title: 'Flutter Calendar Carousel Example'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  DateTime _currentDate = DateTime(2020, 2, 17);
  DateTime _currentDate2 = DateTime(2020, 2, 17);
  String _currentMonth = DateFormat.yMMM().format(DateTime(2020, 2, 17));
  DateTime _targetDateTime = DateTime(2020, 2, 17);
//  List<DateTime> _markedDate = [DateTime(2018, 9, 20), DateTime(2018, 10, 11)];
  static Widget _eventIcon =  Container(
    decoration:  BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(1000)),
        border: Border.all(color: Colors.blue, width: 2.0)),
    child:  Icon(
      Icons.person,
      color: Colors.amber,
    ),
  );

  EventList<Event> _markedDateMap = EventList<Event>();
  CalendarCarousel _calendarCarousel, _calendarCarouselNoHeader;

  @override
  void initState() {
   addMarker(DateTime(2020, 2, 03));
    super.initState();
  }

  addMarker(DateTime startEventDateTime) {

    var eventDateTime = startEventDateTime;

    for(int i=0; i<5; i++) {
      if(eventDateTime.day == 1) {
        eventDateTime = eventDateTime.add(Duration(days: (4)));
      } else {
        eventDateTime = eventDateTime.add(Duration(days: (5)));
      }
      print(eventDateTime.toLocal());
      _markedDateMap.add(
          eventDateTime,
          Event(
            date: eventDateTime,
            title: 'Event $i',
            icon: _eventIcon,
          ));

    }
  }

  @override
  Widget build(BuildContext context) {
    /// Example with custom icon
    _calendarCarousel = CalendarCarousel<Event>(
      onDayPressed: (DateTime date, List<Event> events) {
        this.setState(() => _currentDate = date);
        events.forEach((event) => print(event.title));
      },
      weekendTextStyle: TextStyle(
        color: Colors.red,
      ),
      thisMonthDayBorderColor: Colors.grey,
//          weekDays: null, /// for pass null when you do not want to render weekDays
      headerText: 'Custom Header',
//          markedDates: _markedDate,
      weekFormat: true,
      markedDatesMap: _markedDateMap,
      height: 200.0,
      selectedDateTime: _currentDate2,
      showIconBehindDayText: true,
//          daysHaveCircularBorder: false, /// null for not rendering any border, true for circular border, false for rectangular border
      customGridViewPhysics: NeverScrollableScrollPhysics(),
      markedDateShowIcon: true,
      markedDateIconMaxShown: 2,
      selectedDayTextStyle: TextStyle(
        color: Colors.yellow,
      ),
      todayTextStyle: TextStyle(
        color: Colors.blue,
      ),
      markedDateIconBuilder: (event) {
        return event.icon;
      },
      minSelectedDate: _currentDate.subtract(Duration(days: 360)),
      maxSelectedDate: _currentDate.add(Duration(days: 360)),
      todayButtonColor: Colors.transparent,
      todayBorderColor: Colors.green,
      markedDateMoreShowTotal:
      false, // null for not showing hidden events indicator
//          markedDateIconMargin: 9,
//          markedDateIconOffset: 3,
    );

    /// Example Calendar Carousel without header and custom prev & next button
    _calendarCarouselNoHeader = CalendarCarousel<Event>(
      todayBorderColor: Colors.green,
      onDayPressed: (DateTime date, List<Event> events) {
        this.setState(() => _currentDate2 = date);
        events.forEach((event) => print(event.title));
      },
      daysHaveCircularBorder: true,
      showOnlyCurrentMonthDate: false,
      weekendTextStyle: TextStyle(
        color: Colors.red,
      ),
      thisMonthDayBorderColor: Colors.grey,
      weekFormat: false,
//      firstDayOfWeek: 4,
      markedDatesMap: _markedDateMap,
      height: 420.0,
      selectedDateTime: _currentDate2,
      targetDateTime: _targetDateTime,
      customGridViewPhysics: NeverScrollableScrollPhysics(),
      markedDateCustomShapeBorder: CircleBorder(
          side: BorderSide(color: Colors.yellow)
      ),
      markedDateCustomTextStyle: TextStyle(
        fontSize: 18,
        color: Colors.blue,
      ),
      showHeader: false,
      // markedDateIconBuilder: (event) {
      //   return Container(
      //     color: Colors.blue,
      //   );
      // },
      todayTextStyle: TextStyle(
        color: Colors.blue,
      ),
      todayButtonColor: Colors.yellow,
      selectedDayTextStyle: TextStyle(
        color: Colors.yellow,
      ),
      minSelectedDate: _currentDate.subtract(Duration(days: 360)),
      maxSelectedDate: _currentDate.add(Duration(days: 360)),
      prevDaysTextStyle: TextStyle(
        fontSize: 16,
        color: Colors.pinkAccent,
      ),
      inactiveDaysTextStyle: TextStyle(
        color: Colors.tealAccent,
        fontSize: 16,
      ),
      onCalendarChanged: (DateTime date) {
        this.setState(() {
          _targetDateTime = date;
          _currentMonth = DateFormat.yMMM().format(_targetDateTime);
        });
      },
      onDayLongPressed: (DateTime date) {
        print('long pressed date $date');
      },
    );

    return  Scaffold(
        appBar:  AppBar(
          title:  Text(widget.title),
        ),
        body: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              //custom icon
              Container(
                margin: EdgeInsets.symmetric(horizontal: 16.0),
                child: _calendarCarousel,
              ), // This trailing comma makes auto-formatting nicer for build methods.
              //custom icon without header
              Container(
                margin: EdgeInsets.only(
                  top: 30.0,
                  bottom: 16.0,
                  left: 16.0,
                  right: 16.0,
                ),
                child:  Row(
                  children: <Widget>[
                    Expanded(
                        child: Text(
                          _currentMonth,
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 24.0,
                          ),
                        )),
                    FlatButton(
                      child: Text('PREV'),
                      onPressed: () {
                        setState(() {
                          _targetDateTime = DateTime(_targetDateTime.year, _targetDateTime.month -1);
                          _currentMonth = DateFormat.yMMM().format(_targetDateTime);
                        });
                      },
                    ),
                    FlatButton(
                      child: Text('NEXT'),
                      onPressed: () {
                        setState(() {
                          _targetDateTime = DateTime(_targetDateTime.year, _targetDateTime.month +1);
                          _currentMonth = DateFormat.yMMM().format(_targetDateTime);
                        });
                      },
                    )
                  ],
                ),
              ),
              Container(
                margin: EdgeInsets.symmetric(horizontal: 16.0),
                child: _calendarCarouselNoHeader,
              ), //
            ],
          ),
        ));
  }
}

Upvotes: 3

Related Questions