Coder Social home page Coder Social logo

flutter_clean_calendar's Introduction

flutter_clean_calendar

NOTE:

Due to my current job I'm not able to maintain this project anymore, it's been an exciting journey and thanks to everyone who used it. You can now use fluter_neat_and_clean_calendar by @rwbr who is actively maintaining his project, his package was forked from this one so be sure everything in here would be supported and more You can find me on twitter as @elcharliep

Simple flutter calendar based on flutter_calendar package. Thanks to @AppleEducate for his contributions. You can pull up and down the calendar to show between weekly/monthly calendar. It shows the number of events for thats specific date. It shows the already Done events in other color

Breaking Changes

  • Introduction of 'CleanCalendarEvent' class. This makes the former syntax of the 'Map' that stores the events incompatible.

Screenshot Screenshot

Usage

Embed the 'Calendar' widget in a column. Below the calendar (as the second widget in the Column) place a 'ListView.builder' widget for rendereing the list of events.

Column(
  mainAxisSize: MainAxisSize.max,
  children: <Widget>[
    Container(
      child: Calendar(
        startOnMonday: true,
        weekDays: ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'],
        events: _events,
        onRangeSelected: (range) =>
            print('Range is ${range.from}, ${range.to}'),
        onDateSelected: (date) => _handleNewDate(date),
        isExpandable: true,
        eventDoneColor: Colors.green,
        selectedColor: Colors.pink,
        todayColor: Colors.blue,
        eventColor: Colors.grey,
        locale: 'de_DE',
        todayButtonText: 'Heute',
        expandableDateFormat: 'EEEE, dd. MMMM yyyy',
        dayOfWeekStyle: TextStyle(
            color: Colors.black,
            fontWeight: FontWeight.w800,
            fontSize: 11),
      ),
    ),
    _buildEventList()
  ],
),

...

/// This function [_buildEventList] constructs the list of events of a selected day. This
/// list is rendered below the week view or the month view.
Widget _buildEventList() {
  return Expanded(
    child: ListView.builder(
      padding: EdgeInsets.all(0.0),
      itemBuilder: (BuildContext context, int index) {
        final CleanCalendarEvent event = _selectedEvents[index];
        final String start =
            DateFormat('HH:mm').format(event.startTime).toString();
        final String end =
            DateFormat('HH:mm').format(event.endTime).toString();
        return ListTile(
          contentPadding:
              EdgeInsets.only(left: 2.0, right: 8.0, top: 2.0, bottom: 2.0),
          leading: Container(
            width: 10.0,
            color: event.color,
          ),
          title: Text(event.summary),
          subtitle:
              event.description.isNotEmpty ? Text(event.description) : null,
          trailing: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [Text(start), Text(end)],
          ),
          onTap: () {},
        );
      },
      itemCount: _selectedEvents.length,
    ),
  );
}

For more details see the example.

Properties

/// [onDateSelected] is of type [ValueChanged<DateTime>] and it containes the callback function
///     extecuted when tapping a date
/// [onMonthChanged] is of type [ValueChanged<DateTime>] and it containes the callback function
///     extecuted when changing to another month
/// [onExpandStateChanged] is of type [ValueChanged<bool>] and it contains a callback function
///     executed when the view changes to expanded or to condensed
/// [onRangeSelected] contains a callback function of type [ValueChanged], that gets called on changes
///     of the range (switch to next or previous week or month)
/// [isExpandable] is a [bool]. With this parameter you can control, if the view can expand from week view
///     to month view. Default is [false].
/// [dayBuilder] can contain a [Widget]. If this property is not null (!= null), this widget will get used to
///     render the calenar tiles (so you can customize the view)
/// [hideArrows] is a bool. When set to [true] the arrows to navigate to the next or previous week/month in the
///     top bar well get suppressed. Default is [false].
/// [hideTodayIcon] is a bool. When set to [true] the dispaly of the Today-Icon (button to navigate to today) in the
///     top bar well get suppressed. Default is [false].
/// [hideBottomBar] at the moment has no function. Default is [false].
/// [events] are of type [Map<DateTime, List<CleanCalendarEvent>>]. This data structure containes the events to display
/// [selctedColor] this is the color, applied to the circle on the selcted day
/// [todayColor] this is the color of the date of today
/// [todayButtonText] is a [String]. With this property you can set the caption of the today icon (button to navigate to today).
///     If left empty, the calendar will use the string "Today".
/// [eventColor] lets you optionally specify the color of the event (dot). If the [CleanCaendarEvents] property color is not set, the
///     calendar will use this parameter.
/// [eventDoneColor] with this property you can define the color of "done" events, that is events in the past.
/// [initialDate] is of type [DateTime]. It can contain an optional start date. This is the day, that gets initially selected
///     by the calendar. The default is to not set this parameter. Then the calendar uses [DateTime.now()]
/// [isExpanded] is a bool. If is us set to [true], the calendar gets rendered in month view.
/// [weekDays] contains a [List<String>] defining the names of the week days, so that it is possible to name them according
///     to your current locale.
/// [locale] is a [String]. This setting gets used to format dates according to the current locale.
/// [startOnMonday] is a [bool]. This parameter allows the calendar to determine the first day of the week.
/// [dayOfWeekStyle] is a [TextStyle] for styling the text of the weekday names in the top bar.
/// [bottomBarTextStyle] is a [TextStyle], that sets the style of the text in the bottom bar.
/// [bottomBarArrowColor] can set the [Color] of the arrow to expand/compress the calendar in the bottom bar.
/// [bottomBarColor] sets the [Color] of the bottom bar
/// [expandableDateFormat] defines the formatting of the date in the bottom bar
final ValueChanged<DateTime> onDateSelected;
final ValueChanged<DateTime> onMonthChanged;
final ValueChanged<bool> onExpandStateChanged;
final ValueChanged onRangeSelected;
final bool isExpandable;
final DayBuilder dayBuilder;
final bool hideArrows;
final bool hideTodayIcon;
final Map<DateTime, List<CleanCalendarEvent>> events;
final Color selectedColor;
final Color todayColor;
final String todayButtonText;
final Color eventColor;
final Color eventDoneColor;
final DateTime initialDate;
final bool isExpanded;
final List<String> weekDays;
final String locale;
final bool startOnMonday;
final bool hideBottomBar;
final TextStyle dayOfWeekStyle;
final TextStyle bottomBarTextStyle;
final Color bottomBarArrowColor;
final Color bottomBarColor;
final String expandableDateFormat;

Sample event data

The syntax of the event map changed due to the introduction of the 'CleanCalendarEvent' class.

final Map<DateTime, List<CleanCalendarEvent>> _events = {
    DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day): [
      CleanCalendarEvent('Event A',
          startTime: DateTime(DateTime.now().year, DateTime.now().month,
              DateTime.now().day, 10, 0),
          endTime: DateTime(DateTime.now().year, DateTime.now().month,
              DateTime.now().day, 12, 0),
          description: 'A special event',
          color: Colors.blue[700]),
    ],
    DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day + 2):
        [
      CleanCalendarEvent('Event B',
          startTime: DateTime(DateTime.now().year, DateTime.now().month,
              DateTime.now().day + 2, 10, 0),
          endTime: DateTime(DateTime.now().year, DateTime.now().month,
              DateTime.now().day + 2, 12, 0),
          color: Colors.orange),
      CleanCalendarEvent('Event C',
          startTime: DateTime(DateTime.now().year, DateTime.now().month,
              DateTime.now().day + 2, 14, 30),
          endTime: DateTime(DateTime.now().year, DateTime.now().month,
              DateTime.now().day + 2, 17, 0),
          color: Colors.pink),
    ],
  };

Acknowledgments

Special thanks to @rwbr for adding the new event class to give more flexibility tot he project

flutter_clean_calendar's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

flutter_clean_calendar's Issues

Realtime changes events from Firestore

Hello,

Thank you for this great package!
I was wondering if we could use it we with events extract from Firestore in real time ?
Do you have any example that could help me in this way ?

Many thanks,
Ben

How to change today color?

I want to change this red/orange color of current day. I changed color of past/future days with property. selectedColor: but How i can change color of current day?
I know there is a property todayColor but it is changing only text color of that day, not the whole container/card (widget).
image

Duplicate Date value from Firestore unable to load

Problem:
I have the same date value from Firestore. But only one date value was retrieve. But in static value it will display the same date.

I try to check. I have 10 data , with 3 the same date. The result of looping 7 only. Which it means, in static if there is duplicate date value it will ignore.

Make the Date display colors variable

Can we pls make the text display a variable here?

Text(
                  date != null ? DateFormat("d").format(date!) : '',
                  style: TextStyle(
                      fontSize: 14.0,
                      fontWeight: FontWeight.w400,
                      color: isSelected && this.date != null
                          ? Colors.white // <-- here
                          : Utils.isSameDay(this.date!, DateTime.now())
                              ? todayColor
                              : inMonth
                                  ? Colors.black // <-- here
                                  : Colors
                                      .grey), // Grey color for previous or next months dates
                )

My app is in dark mode and I can't see anything. Thanks!

Error when update version of flutter

Hi ad,
When i update flutter version v1.12.13+hotfix.5-stable i see some error:

Because no versions of flutter_clean_calendar match >1.0.1 <2.0.0 and flutter_clean_calendar 1.0.1 depends on date_utils ^0.1.0+2, flutter_clean_calendar ^1.0.1 requires date_utils ^0.1.0+2.

Because date_utils 0.1.0+2 depends on intl ^0.15.0 and no versions of date_utils match >0.1.0+2 <0.2.0, date_utils ^0.1.0+2 requires intl ^0.15.0.

Thus, flutter_clean_calendar ^1.0.1 requires intl ^0.15.0.

So, because hesty_home_staff depends on both intl ^0.16.0 and flutter_clean_calendar ^1.0.1, version solving failed.
pub get failed (1; So, because hesty_home_staff depends on both intl ^0.16.0 and flutter_clean_calendar ^1.0.1, version solving failed.)

Can you help me resolve it.

expansionButtonRow is not taken language localization

The expansionButtonRow is not taken the language when you change it

I suggest to change this line (line 283)
Utils.fullDayFormat(selectedDate), //show date only in english
for something like this
DateFormat("EEEE MMMM dd, yyyy", widget.locale).format(_selectedDate),

That solve the problem.

Additional, maybe to allow user to write the format they want

Thanks

EVENTCOLOR

It is possible to use different colors/markings in the calendar (eventColor)?

Not show dynamic list event

Inside Stream, Bloc, Redux, Provider builder not render the new map events.

 StoreConnector<AppState, MyCalendarViewModel>(
        distinct: true,
        converter: (store) => MyCalendarViewModel.fromStore(store),
        builder: (_, vm) {
          return  TableCalendar(
                locale: vm.locale.toString(),
                calendarController: _calendarController,
                events: vm.currentEvents,
         );
}):

please help, how i can show markers from api

hello please give me some help I need to show only the markers, but I need to show what comes from the api, this is my model

import 'dart:convert';

class EventsModel {
  final String descricaoJob;
  final String dataDoJob;
  final String horarioInicialDoJob;
  final String horarioFinalDoJob;
  EventsModel({
    required this.descricaoJob,
    required this.dataDoJob,
    required this.horarioInicialDoJob,
    required this.horarioFinalDoJob,
  });

  Map<String, dynamic> toMap() {
    return {
      'descricaoJob': descricaoJob,
      'dataDoJob': dataDoJob,
      'horarioInicialDoJob': horarioInicialDoJob,
      'horarioFinalDoJob': horarioFinalDoJob,
    };
  }

  factory EventsModel.fromMap(Map<String, dynamic> map) {
    return EventsModel(
      descricaoJob: map['descricao'],
      dataDoJob: map['data_acao'],
      horarioInicialDoJob: map['hora_inicial_acao'],
      horarioFinalDoJob: map['hora_final_acao'],
    );
  }

  String toJson() => json.encode(toMap());

  factory EventsModel.fromJson(String source) => EventsModel.fromMap(json.decode(source));
}

this is my method to access the api, it returns a list

 Future<List<EventsModel>> getEvents() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();

    final int? id = sharedPreferences.getInt("idInfluencer");
    final String token = sharedPreferences.getString("token") ?? "";

    final Response result = await _restClient.get<List<EventsModel>>(
        "/job_acoes?influenciador_id=${id.toString()}",
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'Authorization': 'Bearer $token'
        }, decoder: (data) {
      if (data != null) {
        return data.map<EventsModel>((event)=> EventsModel.fromMap(event)).toList();
      }
      return <EventsModel>[];
    });
    if (result.hasError) {
      print(result.statusCode);
      throw "Erro ao buscar dados";
    }

    print(result.body);

    return result.body;
  }
}

how can i pass this list to events?

Dark theme Not supported

Dark theme issue in calendar, it is not workable in dark mode. and there is no option to change the text colour of normal days.

Events Class to event list

Hi , I have an events class thats like this

MyEvents(id: 5a9c120ab3473, 
    title: "Event 1", 
    description: "", 
     image: "", 
     isDone false, 
     classDate: 2019-08-23 00:00:00.000)

I'm getting a list from a database but i cant figure out how to turn it into this format for the calendar (there could be multiple events on each day)

 Map<DateTime, List<Map<String, Object>>> _events2 = {
    DateTime(2019, 8, 24): [
      {'name': 'Event A', 'isDone': true},
    ],
    DateTime(2019, 8, 24): [
      {'name': 'Event A', 'isDone': true},
    ],
    DateTime(2019, 8, 23): [
      {'name': 'Event A', 'isDone': true},
    ],
  };

NoSuchMethodError: The method '[]' was called on null

I found an issue with this package. Here is the details

The following NoSuchMethodError was thrown building Calendar(dirty, state: _CalendarState#e6e49):
The method '[]' was called on null.
Receiver: null
Tried calling: []("Mon")

How to reproduce

  1. Create new flutter project
  2. Add this plugin to pubdev.yaml
  3. Modify build() to contain Calendar()

What I already tried so far

  1. Adding weekDays to Calendar() as per the example
  2. Completely Copy-paste code from the example
  3. None of above fixes the problem

how i can add events?

how i can add events to list?

now hardcoded i mean generatet from a a list with dates

selecting a day in the next month

Hi
Thanks for this package , very helpful!

I found a problem, here is how you reproduce:

Today is Aug 30th.
My calendar shows correct month name value in the top (between the two arrows), i.e. August.
If I select September 1st, the calendar is updated, but the month name value in the top (between the two arrows) still shows August.

Thanks

Overflow when calendar is expanded

Problem:
when the calendar is expanded, and the month has more than 5 rows of dates, a bottom overflowed is presented

Device: IPhone 11 Pro

image

Support null-safety

Hi, thanks for the awesome package.

Dart 2.12 and flutter 2.0.0 are now in stable with the null-safety feature.

Migrating this package to null-safety would help a lot. :)

Here's an official guide from dart doc
https://dart.dev/null-safety/migration-guide

I would love to contribute and help with the migration.

How to customize dates with different colors.

final Data = { DateTime(2020, 10, 10): [{'name': 'Event A', 'isDone': true, 'color':'red'},], DateTime(2020, 10, 11): [{'name': 'Event A', 'isDone': false, 'color':'white'},], DateTime(2020, 10, 12): [{'name': 'Event A', 'isDone': true, 'color':'blue'},], };

Something similar to this. Thanks.
calendar

Package Call Example

Good Morning

I'm trying to use flutter_calendar_clean, but I'm not getting it already installed the package in my application, made the import with the command below:
import 'package: flutter_clean_calendar / flutter_clean_calendar.dart';

But in the documentation I didn't find a way to invoke the calendar I tried basically as follows:

body: Center (child: Calendar ()),

But unfortunately presented error believe I have a correct do so could give me a simple example of how to invoke this package?

Local change

Is it possible to change the calendar local ? If so how to do it ?

Select date doesn't

Hi,

The Today button cannot be customized and doesn't fit my design, I then need to create another one.
If I pass the Today date through a button like this :

RaisedButton(
                        child: Text('Today'),
                        onPressed: () {
                          handleNewDate(DateTime.now());
                        },
                      ),
void handleNewDate(date) {
      selectedDay = date;
      selectedEvents = events[selectedDay] ?? [];
  }

I can retrieve the Today events from events[selectedDay] but the date of today on the calendar is not automatically selected.

How can I achieve that please ?

Better support for larger devices

First, thanks for building this library. It is a wonderfully simple and useful component.

When using this in Flutter for desktop, the interface does not scale well. The monthly calendar view overflows and the weekly view has the wrong proportions.
Screen Shot 2020-07-03 at 20 29 21

Screen Shot 2020-07-03 at 20 29 41

bottom part of grid view getting clipped

WhatsApp Image 2020-07-10 at 10 27 46 PM

on small devices, the ending part is getting clipped. Is there a solution for this? i tried increasing the aspect ratio but it leads to a more compact calendar and hence making it difficult to tap precisely

Is Expanded Don´t work dynamically

Calendar does not change IsExpanded dynamically:

I analyzed the code and probably uses InitState to set the variable isExpanded
again..

void initState () {
super.initState ();

isExpanded = widget? .isExpanded ?? false;

and therefore if the Calendar is still built and has only the isExpanded variable changed, initstate will not be run again.

Just use widget.isExpanded in place of isExpanded throughout the lib widget.

Expanded calendar is not shows dates correctly.

for example if you swipe calendar in unexpanded mode they you can notice it changes month accordingly but if you try to expand it will show false dates or maybe previous month's calendar.

Bug on month transition from a year to another

The function handleSelectedDateAndUserCallback does not take into account whether the selected date is in the next or past year. It checks, if the month of the selected date is higher or lower than the current date's month. The calculation goes wrong, if the selected date falls into next year or previous year.

Remove call to event['isDone']

The events allows the user to pass in a Map<DateTime, List<dynamic>>.
This means the user is free to pass in a list of any type at all at his discretion.
But this will fail if it is not a List<Map> where each element has a isDone property thus restricting the flexibility of the events parameter of the Calendar.

Issue with a useless line of previous calendar

hello it seems that when the month starts at a sunday it will still print a whole line of the previous greyed-out month. this should not be the case as it takes a whole extra week line

left arrow does not move the calendar displayed

In the collapsed mode i.e. the week mode, moving forward works fine - i.e. pressing the right arrow

When I click the left arrow, the selected date and date range is fine - but on the screen the correct dates are not displayed
(Its always week + 1)

When unexpanding (shrinking), the week does not change to the week containing the selected day.

To reproduce:

  1. Have the calendar in the expanded form
  2. Select a day in a week other than the one that has the current selected day.
  3. Swipe up on the calendar to shrink it.
  4. (NOTE) The week displayed does not have the current selected day in it.
  5. Swipe left on week.
  6. (NOTE) The week updates with the week before the selected day and selects the matching weekday
  7. Swipe right.
  8. (NOTE) The week now shows the correct week with the day selected.

Running example code gives message "Your app isn't using AndroidX"

The following message appears when running the example code found in example folder.
[!] Your app isn't using AndroidX.
To avoid potential build failures, you can quickly migrate your app by following the steps on https://goo.gl/CP92wY .

flutter doctor result (run flutter doctor in terminal)

Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 1.20.3, on Microsoft Windows [Versión 10.0.17134.590], locale es-PE)

[√] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[!] Android Studio (version 3.6)
X Unable to determine bundled Java version.
[√] Android Studio (version 4.0)
[!] Connected device
! No devices available

! Doctor found issues in 2 categories.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.