Flutter日历展示插件table_calendar_sandamil的使用
Flutter日历展示插件table_calendar_sandamil的使用
特性
- 支持双事件
- 提供广泛的、易于使用的API
- 自定义构建器以实现真正灵活的UI
- 完全的程序化控制通过CalendarController
- 动态事件
- 节假日接口
- 多语言支持
- 垂直自动调整大小
- 美丽的动画效果
- 手势处理
- 多种日历格式
- 多种周几格式
- 指定可用日期范围
- 开箱即用的配置良好的UI
安装
在pubspec.yaml
文件中添加依赖项:
dependencies:
table_calendar_sandamil: ^2.0.0
然后在项目中导入该包:
import 'package:table_calendar_sandamil/table_calendar_sandamil.dart';
最后创建一个带有CalendarController
的TableCalendar
:
class _MyHomePageState extends State<MyHomePage> {
CalendarController _calendarController;
[@override](/user/override)
void initState() {
super.initState();
_calendarController = CalendarController();
}
[@override](/user/override)
void dispose() {
_calendarController.dispose();
super.dispose();
}
[@override](/user/override)
Widget build(BuildContext context) {
return TableCalendar(
calendarController: _calendarController,
);
}
}
多语言支持
Table Calendar
支持多语言。要将日历显示为所需的语言,可以使用locale
属性。如果不指定,则会使用默认语言。
完整示例代码
// Copyright (c) 2019 Aleksander Woźniak
// Licensed under Apache License v2.0
import 'package:flutter/material.dart';
import 'package:intl/date_symbol_data_local.dart';
import 'package:table_calendar_sandamil/table_calendar_sandamil.dart';
// 示例节假日
final Map<DateTime, List> _holidays = {
DateTime(2020, 1, 1): ['新年'],
DateTime(2020, 1, 6): ['主显节'],
DateTime(2020, 2, 14): ['情人节'],
DateTime(2020, 4, 21): ['复活节星期天'],
DateTime(2020, 4, 22): ['复活节星期一'],
};
void main() {
initializeDateFormatting().then((_) => runApp(MyApp()));
}
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: 'Table Calendar Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Table Calendar Demo'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, this.title}) : super(key: key);
final String? title;
[@override](/user/override)
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
Map<DateTime, List>? _events;
List? _selectedEvents;
late AnimationController _animationController;
late CalendarController _calendarController;
[@override](/user/override)
void initState() {
super.initState();
final _selectedDay = DateTime.now();
_events = {
_selectedDay.subtract(Duration(days: 30)): [
'事件A0',
'事件B0',
'事件C0'
],
_selectedDay.subtract(Duration(days: 27)): ['事件A1'],
_selectedDay.subtract(Duration(days: 20)): [
'事件A2',
'事件B2',
'事件C2',
'事件D2'
],
_selectedDay.subtract(Duration(days: 16)): ['事件A3', '事件B3'],
_selectedDay.subtract(Duration(days: 10)): [
'事件A4',
'事件B4',
'事件C4'
],
_selectedDay.subtract(Duration(days: 4)): [
'事件A5',
'事件B5',
'事件C5'
],
_selectedDay.subtract(Duration(days: 2)): ['事件A6', '事件B6'],
_selectedDay: ['事件A7', '事件B7', '事件C7', '事件D7'],
_selectedDay.add(Duration(days: 1)): [
'事件A8',
'事件B8',
'事件C8',
'事件D8'
],
_selectedDay.add(Duration(days: 3)):
Set.from(['事件A9', '事件A9', '事件B9']).toList(),
_selectedDay.add(Duration(days: 7)): [
'事件A10',
'事件B10',
'事件C10'
],
_selectedDay.add(Duration(days: 11)): ['事件A11', '事件B11'],
_selectedDay.add(Duration(days: 17)): [
'事件A12',
'事件B12',
'事件C12',
'事件D12'
],
_selectedDay.add(Duration(days: 22)): ['事件A13', '事件B13'],
_selectedDay.add(Duration(days: 26)): [
'事件A14',
'事件B14',
'事件C14'
],
};
_selectedEvents = _events?[_selectedDay] ?? [];
_calendarController = CalendarController();
_animationController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 400),
);
_animationController.forward();
}
[@override](/user/override)
void dispose() {
_animationController.dispose();
_calendarController.dispose();
super.dispose();
}
void _onDaySelected(DateTime day, List events, List marks, List holidays) {
print('CALLBACK: _onDaySelected');
setState(() {
_selectedEvents = events;
});
}
void _onVisibleDaysChanged(
DateTime first, DateTime last, CalendarFormat format) {
print('CALLBACK: _onVisibleDaysChanged');
}
void _onCalendarCreated(
DateTime first, DateTime last, CalendarFormat format) {
print('CALLBACK: _onCalendarCreated');
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title ?? '标题'),
),
body: Column(
mainAxisSize: MainAxisSize.max,
children: <Widget>[
// 切换以下两行以测试TableCalendar的不同设置
//-----------------------
_buildTableCalendar(),
// _buildTableCalendarWithBuilders(),
const SizedBox(height: 8.0),
_buildButtons(),
const SizedBox(height: 8.0),
Expanded(child: _buildEventList()),
],
),
);
}
// 简单的TableCalendar配置(使用样式)
Widget _buildTableCalendar() {
return TableCalendar(
calendarController: _calendarController,
events: _events ?? {},
holidays: _holidays,
startingDayOfWeek: StartingDayOfWeek.monday,
calendarStyle: CalendarStyle(
selectedColor: Colors.deepOrange,
todayColor: Colors.deepOrange,
markersColor: Colors.brown,
outsideDaysVisible: false,
),
headerStyle: HeaderStyle(
formatButtonTextStyle:
TextStyle().copyWith(color: Colors.white, fontSize: 15.0),
formatButtonDecoration: BoxDecoration(
color: Colors.deepOrange[400],
borderRadius: BorderRadius.circular(16.0),
),
),
onDaySelected: _onDaySelected,
onVisibleDaysChanged: _onVisibleDaysChanged,
onCalendarCreated: _onCalendarCreated,
);
}
// 更高级的TableCalendar配置(使用构建器和样式)
/*
Widget _buildTableCalendarWithBuilders() {
return TableCalendar(
locale: 'pl_PL',
calendarController: _calendarController,
events: _events ?? {},
holidays: _holidays,
initialCalendarFormat: CalendarFormat.month,
formatAnimation: FormatAnimation.slide,
startingDayOfWeek: StartingDayOfWeek.sunday,
availableGestures: AvailableGestures.all,
availableCalendarFormats: const {
CalendarFormat.month: '',
CalendarFormat.week: '',
},
calendarStyle: CalendarStyle(
outsideDaysVisible: false,
weekendStyle: TextStyle().copyWith(color: Colors.blue[800]),
holidayStyle: TextStyle().copyWith(color: Colors.blue[800]),
),
daysOfWeekStyle: DaysOfWeekStyle(
weekendStyle: TextStyle().copyWith(color: Colors.blue[600]),
),
headerStyle: HeaderStyle(
centerHeaderTitle: true,
formatButtonVisible: false,
),
builders: CalendarBuilders(
selectedDayBuilder: (context, date, _) {
return FadeTransition(
opacity: Tween(begin: 0.0, end: 1.0).animate(_animationController),
child: Container(
margin: const EdgeInsets.all(4.0),
padding: const EdgeInsets.only(top: 5.0, left: 6.0),
color: Colors.deepOrange[300],
width: 100,
height: 100,
child: Text(
'${date.day}',
style: TextStyle().copyWith(fontSize: 16.0),
),
),
);
},
todayDayBuilder: (context, date, _) {
return Container(
margin: const EdgeInsets.all(4.0),
padding: const EdgeInsets.only(top: 5.0, left: 6.0),
color: Colors.amber[400],
width: 100,
height: 100,
child: Text(
'${date.day}',
style: TextStyle().copyWith(fontSize: 16.0),
),
);
},
markersBuilder: (context, date, events, holidays) {
final children = [];
if (events.isNotEmpty) {
children.add(
Positioned(
right: 1,
bottom: 1,
child: _buildEventsMarker(date, events),
),
);
}
if (holidays.isNotEmpty) {
children.add(
Positioned(
right: -2,
top: -2,
child: _buildHolidaysMarker(),
),
);
}
return children;
},
),
onDaySelected: (date, events, holidays) {
_onDaySelected(date, events, holidays);
_animationController.forward(from: 0.0);
},
onVisibleDaysChanged: _onVisibleDaysChanged,
onCalendarCreated: _onCalendarCreated,
);
}
Widget _buildEventsMarker(DateTime date, List events) {
return AnimatedContainer(
duration: const Duration(milliseconds: 300),
decoration: BoxDecoration(
shape: BoxShape.rectangle,
color: _calendarController.isSelected(date)
? Colors.brown[500]
: _calendarController.isToday(date)
? Colors.brown[300]
: Colors.blue[400],
),
width: 16.0,
height: 16.0,
child: Center(
child: Text(
'${events.length}',
style: TextStyle().copyWith(
color: Colors.white,
fontSize: 12.0,
),
),
),
);
}
Widget _buildHolidaysMarker() {
return Icon(
Icons.add_box,
size: 20.0,
color: Colors.blueGrey[800],
);
}
*/
Widget _buildButtons() {
final dateTime =
_events?.keys.elementAt((_events?.length ?? 2) - 2) ?? DateTime.now();
return Column(
children: <Widget>[
Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
TextButton(
child: Text('月'),
onPressed: () {
setState(() {
_calendarController.setCalendarFormat(CalendarFormat.month);
});
},
),
TextButton(
child: Text('两周'),
onPressed: () {
setState(() {
_calendarController
.setCalendarFormat(CalendarFormat.twoWeeks);
});
},
),
TextButton(
child: Text('周'),
onPressed: () {
setState(() {
_calendarController.setCalendarFormat(CalendarFormat.week);
});
},
),
],
),
const SizedBox(height: 8.0),
TextButton(
child: Text(
'设置日期 ${dateTime.day}-${dateTime.month}-${dateTime.year}'),
onPressed: () {
_calendarController.setSelectedDay(
DateTime(dateTime.year, dateTime.month, dateTime.day),
runCallback: true,
);
},
),
],
);
}
Widget _buildEventList() {
return ListView(
children: _selectedEvents
?.map((event) => Container(
decoration: BoxDecoration(
border: Border.all(width: 0.8),
borderRadius: BorderRadius.circular(12.0),
),
margin: const EdgeInsets.symmetric(
horizontal: 8.0, vertical: 4.0),
child: ListTile(
title: Text(event.toString()),
onTap: () => print('$event 被点击!'),
),
))
.toList() ??
[],
);
}
}
更多关于Flutter日历展示插件table_calendar_sandamil的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复
更多关于Flutter日历展示插件table_calendar_sandamil的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
table_calendar_sandamil
是一个基于 table_calendar
的 Flutter 日历插件,它提供了更多的自定义选项和功能。使用这个插件,你可以轻松地在 Flutter 应用中展示日历,并且可以根据需求进行自定义。
安装
首先,你需要在 pubspec.yaml
文件中添加依赖:
dependencies:
flutter:
sdk: flutter
table_calendar_sandamil: ^3.0.0
然后运行 flutter pub get
来安装依赖。
基本使用
下面是一个简单的例子,展示如何使用 table_calendar_sandamil
来展示一个日历:
import 'package:flutter/material.dart';
import 'package:table_calendar_sandamil/table_calendar_sandamil.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Table Calendar Sandamil Example'),
),
body: CalendarExample(),
),
);
}
}
class CalendarExample extends StatefulWidget {
@override
_CalendarExampleState createState() => _CalendarExampleState();
}
class _CalendarExampleState extends State<CalendarExample> {
CalendarFormat _calendarFormat = CalendarFormat.month;
DateTime _focusedDay = DateTime.now();
DateTime? _selectedDay;
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: TableCalendarSandamil(
firstDay: DateTime.utc(2020, 1, 1),
lastDay: DateTime.utc(2030, 12, 31),
focusedDay: _focusedDay,
calendarFormat: _calendarFormat,
selectedDayPredicate: (day) {
return isSameDay(_selectedDay, day);
},
onDaySelected: (selectedDay, focusedDay) {
setState(() {
_selectedDay = selectedDay;
_focusedDay = focusedDay;
});
},
onFormatChanged: (format) {
setState(() {
_calendarFormat = format;
});
},
onPageChanged: (focusedDay) {
_focusedDay = focusedDay;
},
),
);
}
}
主要参数和功能
firstDay
和lastDay
: 定义日历的日期范围。focusedDay
: 当前聚焦的日期。calendarFormat
: 日历的展示格式,可以是month
、week
或twoWeeks
。selectedDayPredicate
: 用于判断某一天是否被选中。onDaySelected
: 当某一天被选中时触发的回调。onFormatChanged
: 当日历格式改变时触发的回调。onPageChanged
: 当日历页面改变时触发的回调。
自定义样式
table_calendar_sandamil
提供了丰富的自定义选项,你可以通过 calendarStyle
参数来自定义日历的外观:
TableCalendarSandamil(
// 其他参数...
calendarStyle: CalendarStyle(
outsideDaysVisible: false,
weekendTextStyle: TextStyle().copyWith(color: Colors.red),
selectedDecoration: BoxDecoration(
color: Colors.blue,
shape: BoxShape.circle,
),
todayDecoration: BoxDecoration(
color: Colors.green,
shape: BoxShape.circle,
),
),
)
事件标记
你还可以在日历上标记特定日期的事件:
TableCalendarSandamil(
// 其他参数...
eventLoader: (day) {
// 返回一个事件列表
if (day.day == DateTime.now().day) {
return ['Event 1', 'Event 2'];
}
return [];
},
)