Created
October 30, 2019 11:25
-
-
Save aleksanderwozniak/1367892cbe39c25afda403b2300652ca to your computer and use it in GitHub Desktop.
Flutter - providing dynamic data to TableCalendar widget
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
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; | |
StreamController<Map<DateTime, List>> _streamController; | |
@override | |
void initState() { | |
super.initState(); | |
_calendarController = CalendarController(); | |
_streamController = StreamController(); | |
_fetchEvents(); | |
} | |
@override | |
void dispose() { | |
_calendarController.dispose(); | |
_streamController.close(); | |
super.dispose(); | |
} | |
// Fetches two events on two random days within the current month | |
void _fetchEvents() { | |
final random = Random(); | |
final randomIntA = random.nextInt(13) + 1; | |
final randomIntB = random.nextInt(13) + 14; | |
final now = DateTime.now(); | |
final events = { | |
DateTime(now.year, now.month, randomIntA): ['Random event #$randomIntA'], | |
DateTime(now.year, now.month, randomIntB): ['Random event #$randomIntB'], | |
}; | |
_streamController.add(events); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar(title: Text('TableCalendar Dynamic Demo')), | |
body: Center( | |
child: Column( | |
children: <Widget>[ | |
StreamBuilder<Map<DateTime, List>>( | |
stream: _streamController.stream, | |
builder: (context, snapshot) { | |
if (!snapshot.hasData) { | |
return SizedBox( | |
height: 100.0, | |
width: 100.0, | |
child: Center(child: CircularProgressIndicator()), | |
); | |
} | |
final events = snapshot.data; | |
return TableCalendar( | |
calendarController: _calendarController, | |
events: events, | |
); | |
}, | |
), | |
const SizedBox(height: 32.0), | |
RaisedButton( | |
onPressed: _fetchEvents, | |
child: Text('Fetch events'), | |
), | |
], | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment