Skip to content

Instantly share code, notes, and snippets.

@aleksanderwozniak
Created November 8, 2019 09:44
Show Gist options
  • Save aleksanderwozniak/e9eb98bf28bd9fbb336039e1936c59aa to your computer and use it in GitHub Desktop.
Save aleksanderwozniak/e9eb98bf28bd9fbb336039e1936c59aa to your computer and use it in GitHub Desktop.
Flutter - adding a new event to TableCalendar widget
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:table_calendar/table_calendar.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'TableCalendar Demo',
theme: ThemeData(primarySwatch: Colors.indigo),
home: HomeScreen(),
);
}
}
class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
CalendarController _calendarController;
Map<DateTime, List> _events;
@override
void initState() {
super.initState();
_calendarController = CalendarController();
_events = {
DateTime.utc(2019, 11, 5, 12): ['Event 1'],
DateTime.utc(2019, 11, 6, 12): ['Event 2'],
};
}
@override
void dispose() {
_calendarController.dispose();
super.dispose();
}
// Adds a new random event to currently selected day
void _addEvent() {
final random = Random();
final randomValue = random.nextInt(99) + 1;
final day = _calendarController.selectedDay;
final event = 'Random event $randomValue';
setState(() {
_events.update(
day,
(previousEvents) => previousEvents..add(event),
ifAbsent: () => [event],
);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('TableCalendar Add Event Demo')),
body: Center(
child: Column(
children: <Widget>[
TableCalendar(
calendarController: _calendarController,
events: _events,
),
RaisedButton(
onPressed: _addEvent,
child: Text('Add event'),
),
RaisedButton(
onPressed: () => print(_calendarController.visibleEvents[_calendarController.selectedDay]),
child: Text('Print selected events'),
),
RaisedButton(
onPressed: () => print(_events),
child: Text('Print all events'),
),
],
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment