Flutter日历展示与管理插件calendar_awesome的使用

Flutter日历展示与管理插件calendar_awesome的使用

calendar_awesome

一个支持自定义的日历小部件(Jalali 和 Gregorian)。

Image

安装

运行以下命令:

flutter pub add calendar_awesome

或者在 pubspec.yaml 文件中添加依赖:

dependencies:
  calendar_awesome: ^0.0.1

简单使用

import 'package:calendar_awesome/calendar_awesome.dart';

CalendarAwesome(
  date: const GregorianDate(2024, 8), /// 或者 JalaliDate(1403,5)
  onChange: (onChangeParam) {
    print(onChangeParam.date);
    print(onChangeParam.tasks);
    print(onChangeParam.events);
    print(onChangeParam.holidays);
  }
)

CalendarAwesome 属性

属性 描述 类型 必须 默认值
date 确定默认日历的类型、年份和月份。例如:GregorianDate(2024,8) 或 JalaliDate(1403,5) CustomDate 是 无
events 一个包含 EventClass 的列表,会在日期上方显示为一个点 List 否 []
tasks 一个包含 TaskClass 的列表,会在日期下方线性显示 List 否 []
holidays 一个包含 HolidayClass 的列表,会将日期标记为节假日 List 否 []
showWeekend 是否显示周末 bool 否 true
activeSelectDate 用户是否可以选择日期 bool 否 true
calendarStyle 获取 CalendarStyle 类以自定义UI CalendarStyle 否 CalendarStyle()
header 自定义头部而不是默认头部 Widget Function(PageController, Month) 否 null
onChange 当点击某一天时,返回该天的值 void Function(OnChangeParam) 是 无

CalendarStyle 属性

属性 描述 类型 必须 默认值
weekendStyle 节假日文本样式 TextStyle 否 null
weekdayStyle 星期几文本样式 TextStyle 否 null
textWeekdayStyle 星期几文本样式 TextStyle 否 TextStyle(color: Colors.black)
direction 日历方向,从左到右或从右到左 TextDirection 否 TextDirection.ltr
textWeekdayAngle 星期几文字旋转角度 double 否 0.7
todayColor 今天颜色 Color 否 Color.fromARGB(255, 70, 39, 156)
todayStyle 今天文本样式 TextStyle 否 null
taskColor 任务颜色(在日期下方显示) Color 否 Colors.greenAccent
selectDayWidth 选中日期圆圈的厚度 double 否 1.2
persianText 是否使用波斯文 bool 否 false
scrollDirection 页面之间的滚动方向 Axis 否 null
animationDuration 页面间移动的动画持续时间 Duration 否 null
animationCurve 页面间移动的动画类型 Curve 否 null
selectDayColor 选中日期圆圈的颜色 Color 否 null
weekdaysText 星期几文字列表 List 否 [“Sun”, “Mon”, “Tue”, “Wed”, “Thur”, “Fri”, “Sat”]

示例代码

import 'package:calendar_awesome/calendar_awesome.dart';
import 'package:delayed_display/delayed_display.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: MainScreen(),
    );
  }
}

class MainScreen extends StatefulWidget {
  const MainScreen({super.key});

  [@override](/user/override)
  State<MainScreen> createState() => _MainScreenState();
}

class _MainScreenState extends State<MainScreen> {
  final DateTime _dateTime = DateTime.now();

  List<EventClass> events = [];

  List<TaskClass> tasks = [];

  List<HolidayClass> holiday = [];

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text('Calendar Awesome Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CalendarAwesome(
              date: GregorianDate(_dateTime.year, _dateTime.month),
              showWeekend: true,
              activeSelectDate: true,

              holidays: [
                HolidayClass<String>(
                  id: 0,
                  date: _dateTime.add(const Duration(days: 2)),
                  data: "Holiday 1",
                ),
                HolidayClass<String>(
                  id: 1,
                  date: _dateTime.add(const Duration(days: 37)),
                  data: "Holiday 2",
                ),
              ],

              /// 任务列表
              tasks: [
                TaskClass<String>(
                  id: 0,
                  date: _dateTime.add(const Duration(days: 7)),
                  data: "Task 1",
                ),
                TaskClass<String>(
                  id: 1,
                  date: _dateTime.add(const Duration(days: 4)),
                  data: "Task 2",
                ),
                TaskClass<String>(
                  id: 2,
                  date: _dateTime.add(const Duration(days: 31)),
                  data: "Task 3",
                ),
              ],

              events: [
                EventClass<String>(
                  id: 0,
                  date: _dateTime.add(const Duration(days: 7)),
                  color: Colors.blue,
                  data: "Event 1",
                ),
                EventClass<String>(
                  id: 0,
                  date: _dateTime.add(const Duration(days: 7)),
                  color: Colors.orange,
                  data: "Event 2",
                ),
                EventClass<String>(
                  id: 0,
                  date: _dateTime.add(const Duration(days: 17)),
                  color: Colors.green,
                  data: "Event 3",
                ),
                EventClass<String>(
                  id: 0,
                  date: _dateTime.add(const Duration(days: 39)),
                  color: Colors.green,
                  data: "Event 4",
                ),
              ],

              calendarStyle: const CalendarStyle(
                animationDuration: Duration(seconds: 1),
                weekendStyle: TextStyle(
                  color: Colors.red,
                  fontSize: 20,
                ),
                weekdayStyle: TextStyle(
                  fontSize: 18,
                  color: Colors.black,
                ),
                todayStyle: TextStyle(color: Colors.white, fontSize: 20),
                todayColor: Colors.indigo,
                textWeekdayStyle: TextStyle(
                  fontSize: 16,
                  color: Colors.black,
                ),
                selectDayWidth: 3,
                selectDayColor: Colors.orange,
                taskColor: Colors.greenAccent,
                textWeekdayAngle: 0.2,
                scrollDirection: Axis.horizontal,
                weekdaysText: [
                  'Sun',
                  'Mon',
                  'Tue',
                  'Wed',
                  'Thur',
                  'Fri',
                  'Sat'
                ],
                animationCurve: Curves.bounceIn,
                persianText: false,
                direction: TextDirection.ltr,
              ),
              onChange: (OnChangeParam onChangeParam) {
                setState(() {
                  events = onChangeParam.events;
                  tasks = onChangeParam.tasks;
                  holiday = onChangeParam.holidays;
                  // print(onChangeParam.date);
                });
              },
            ),
            AspectRatio(
              aspectRatio: 2 / 1,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  /// 任务列表
                  Expanded(
                    child: ListView.builder(
                      itemCount: tasks.length,
                      itemBuilder: (BuildContext context, int index) => MyCard(
                        text: tasks[index].data,
                        color: Colors.lightGreen,
                      ),
                    ),
                  ),

                  /// 事件列表
                  Expanded(
                    child: ListView.builder(
                      itemCount: events.length,
                      itemBuilder: (BuildContext context, int index) => MyCard(
                        text: events[index].data,
                        color: events[index].color,
                      ),
                    ),
                  ),

                  /// 节假日列表
                  Expanded(
                    child: ListView.builder(
                      itemCount: holiday.length,
                      itemBuilder: (BuildContext context, int index) => MyCard(
                        text: holiday[index].data,
                        color: Colors.redAccent,
                      ),
                    ),
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}

class MyCard extends StatelessWidget {
  final String text;
  final Color color;

  const MyCard({super.key, required this.text, required this.color});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return DelayedDisplay(
      delay: const Duration(milliseconds: 110),
      child: Container(
        padding: const EdgeInsets.all(5),
        margin: const EdgeInsets.all(5),
        decoration: BoxDecoration(
            color: Colors.white70,
            borderRadius: BorderRadius.circular(10),
            boxShadow: [
              BoxShadow(
                color: color,
                blurRadius: 12,
                offset: const Offset(1, 5),
              )
            ],
            border: Border.all(color: color, width: 3)),
        alignment: Alignment.center,
        child: Text(
          text,
          style: TextStyle(color: color),
        ),
      ),
    );
  }
}

class g extends StatelessWidget {
  const g({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return CalendarAwesome(
      date: const GregorianDate(2024, 8),

      /// 或者 JalaliDate(1403,5)
      onChange: (onChangeParam) {
        print(onChangeParam.date);
        print(onChangeParam.tasks);
        print(onChangeParam.events);
        print(onChangeParam.holidays);
      },
    );
  }
}

更多关于Flutter日历展示与管理插件calendar_awesome的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter日历展示与管理插件calendar_awesome的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter项目中使用calendar_awesome插件来展示和管理日历的示例代码。这个插件提供了强大的日历功能,包括日期选择、事件展示等。

首先,确保你已经在pubspec.yaml文件中添加了calendar_awesome依赖:

dependencies:
  flutter:
    sdk: flutter
  calendar_awesome: ^3.0.0  # 请确保使用最新版本

然后,运行flutter pub get来安装依赖。

接下来,是一个简单的示例代码,展示了如何使用calendar_awesome来展示一个日历,并在日历上标记一些事件:

import 'package:flutter/material.dart';
import 'package:calendar_awesome/calendar_awesome.dart';
import 'package:intl/intl.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Calendar Awesome Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: CalendarPage(),
    );
  }
}

class CalendarPage extends StatefulWidget {
  @override
  _CalendarPageState createState() => _CalendarPageState();
}

class _CalendarPageState extends State<CalendarPage> {
  final DateFormat _dateFormat = DateFormat('yyyy-MM-dd');

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Calendar Awesome Demo'),
      ),
      body: CalendarAwesome(
        // 当前显示的月份
        initialSelectedDate: DateTime.now(),
        // 日历事件
        events: _getEvents(),
        // 日期选择回调
        onDateSelected: (date, events) {
          print('Selected date: ${_dateFormat.format(date)}');
          print('Events: $events');
        },
        // 日期长按回调
        onDateLongPressed: (date, events) {
          print('Long pressed date: ${_dateFormat.format(date)}');
          print('Events: $events');
        },
        // 日历样式
        calendarStyle: CalendarStyle(
          todayColor: Colors.red,
          selectedColor: Colors.blue,
          markedDateBackgroundColor: Colors.grey[200]!,
          markedDateTextStyle: TextStyle(color: Colors.black),
          todayCircleColor: Colors.white,
          selectedCircleColor: Colors.white,
        ),
        // 星期样式
        headerStyle: HeaderStyle(
          centerHeaderTitle: true,
          formatWeekday: (day) => DateFormat('EEE').format(DateTime(2023, day)),
          decoration: BoxDecoration(
            color: Colors.blueGrey[100]!,
          ),
          titleTextStyle: TextStyle(color: Colors.black, fontSize: 20),
          weekdayTextStyle: TextStyle(color: Colors.black),
        ),
      ),
    );
  }

  // 获取日历事件
  List<CalendarEvent> _getEvents() {
    return [
      CalendarEvent(
        date: DateTime(2023, 10, 5),
        title: 'Event 1',
        description: 'This is the first event.',
      ),
      CalendarEvent(
        date: DateTime(2023, 10, 15),
        title: 'Event 2',
        description: 'This is the second event.',
      ),
      CalendarEvent(
        date: DateTime(2023, 10, 25),
        title: 'Event 3',
        description: 'This is the third event.',
      ),
      // 可以添加更多事件
    ];
  }
}

在这个示例中:

  • CalendarAwesome组件用于显示日历。
  • initialSelectedDate属性设置日历初始显示的日期。
  • events属性接收一个CalendarEvent列表,用于在日历上标记事件。
  • onDateSelected和onDateLongPressed回调用于处理日期选择和长按事件。
  • calendarStyle和headerStyle属性用于自定义日历和头部的样式。

你可以根据需要调整这些属性和事件列表来满足你的需求。希望这个示例能帮助你快速上手calendar_awesome插件!

回到顶部