Flutter日历选择插件custom_calendar_picker的使用

发布于 1周前 作者 vueper 来自 Flutter

Flutter日历选择插件custom_calendar_picker的使用

Intro

custom_calendar_picker 是一个高度可定制的日历选择器插件,允许开发者根据需要创建日期列表或日期范围选择器。

List Example

Range Example

How to use

参数说明

在使用 custom_calendar_picker 时,您需要提供以下参数:

// DateList or DateRange
final ReturnDateType returnDateType;
// if returnDateType is list, initial value
final List<DateTime>? initialDateList;
// if returnDateType is range, initial value
final DateTimeRange? initialDateRange;
final Color selectedColor;
final Color rangeColor;
final Color? selectedFontColor;
//light or dark
final CalenderThema calenderThema;
final BorderRadius borderRadius;
final Color buttonColor;
final String buttonText;
final Color buttonTextColor;

示例代码

下面是一个完整的示例demo,展示了如何在Flutter应用中使用 custom_calendar_picker 插件。

main.dart

import 'package:flutter/material.dart';
import 'package:custom_calender_picker/custom_calender_picker.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const CustomCalenderPickerExample(),
    );
  }
}

class CustomCalenderPickerExample extends StatefulWidget {
  const CustomCalenderPickerExample({Key? key}) : super(key: key);

  @override
  State<CustomCalenderPickerExample> createState() => _DatePickerPageState();
}

class _DatePickerPageState extends State<CustomCalenderPickerExample> {
  List<DateTime> eachDateTime = [];
  DateTimeRange? rangeDateTime;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('Custom Date Picker'),
      ),
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 12),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            ElevatedButton(
              onPressed: () async {
                var result = await showDialog(
                  context: context,
                  builder: (context) => Dialog(
                    insetPadding: const EdgeInsets.symmetric(
                      horizontal: 20,
                    ),
                    shape: const RoundedRectangleBorder(
                      borderRadius: BorderRadius.all(
                        Radius.circular(20),
                      ),
                    ),
                    child: CustomCalenderPicker(
                      returnDateType: ReturnDateType.list,
                      initialDateList: eachDateTime,
                      calenderThema: CalenderThema.white,
                    ),
                  ),
                );
                if (result != null) {
                  if (result is List<DateTime>) {
                    setState(() {
                      eachDateTime.clear();
                      eachDateTime.addAll(result);
                    });
                  }
                }
              },
              child: const Text('Dialog Example'),
            ),
            ...List.generate(
              eachDateTime.length,
              (index) => Text(
                eachDateTime[index].toString().substring(0, 10),
              ),
            ),
            const SizedBox(
              height: 20,
            ),
            ElevatedButton(
              onPressed: () async {
                var result = await showModalBottomSheet(
                  isScrollControlled: true,
                  shape: const RoundedRectangleBorder(
                    borderRadius: BorderRadius.vertical(
                      top: Radius.circular(20),
                      bottom: Radius.zero,
                    ),
                  ),
                  context: context,
                  builder: (context) => CustomCalenderPicker(
                    returnDateType: ReturnDateType.range,
                    initialDateRange: rangeDateTime,
                    calenderThema: CalenderThema.dark,
                    rangeColor: Colors.grey.withOpacity(.3),
                    borderRadius: const BorderRadius.vertical(
                      top: Radius.circular(20),
                      bottom: Radius.zero,
                    ),
                  ),
                );
                if (result != null) {
                  if (result is DateTimeRange) {
                    setState(() {
                      rangeDateTime = result;
                    });
                  }
                }
              },
              child: const Text('Bottom Sheet Example'),
            ),
            Text(rangeDateTime == null
                ? ''
                : '${rangeDateTime!.start.toString().substring(0, 10)} ~ ${rangeDateTime!.end.toString().substring(0, 10)}')
          ],
        ),
      ),
    );
  }
}

运行效果

  • Dialog Example: 点击按钮后弹出对话框,可以选择多个日期,选中的日期会显示在界面上。
  • Bottom Sheet Example: 点击按钮后弹出底部表单,可以选择日期范围,选中的日期范围会显示在界面上。

通过上述代码和说明,您可以快速上手并使用 custom_calendar_picker 插件来实现自定义的日历选择功能。希望这对您有所帮助!


更多关于Flutter日历选择插件custom_calendar_picker的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter日历选择插件custom_calendar_picker的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter应用中使用custom_calendar_picker插件的示例代码。这个插件允许用户选择一个日期范围或者单个日期,非常适合需要日历选择功能的场景。

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

dependencies:
  flutter:
    sdk: flutter
  custom_calendar_picker: ^x.y.z  # 请替换为最新版本号

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

接下来是一个完整的示例代码,展示如何使用custom_calendar_picker来选择日期范围:

import 'package:flutter/material.dart';
import 'package:custom_calendar_picker/custom_calendar_picker.dart';

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

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

class CalendarPickerDemo extends StatefulWidget {
  @override
  _CalendarPickerDemoState createState() => _CalendarPickerDemoState();
}

class _CalendarPickerDemoState extends State<CalendarPickerDemo> {
  DateTime? startDate;
  DateTime? endDate;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Calendar Picker Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Selected Date Range:',
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(height: 20),
            Text(
              '${startDate != null ? startDate!.toLocal().toString() : 'Start Date'} - ${endDate != null ? endDate!.toLocal().toString() : 'End Date'}',
              style: TextStyle(fontSize: 18),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                _selectDateRange(context);
              },
              child: Text('Select Date Range'),
            ),
          ],
        ),
      ),
    );
  }

  void _selectDateRange(BuildContext context) async {
    final DateTime? resultStartDate = await showDatePicker(
      context: context,
      initialDate: startDate ?? DateTime.now(),
      firstDate: DateTime(2000),
      lastDate: DateTime(2101),
    );

    if (resultStartDate != null && (resultStartDate != startDate)) {
      setState(() {
        startDate = resultStartDate;
      });

      final DateTime? resultEndDate = await showDatePicker(
        context: context,
        initialDate: endDate ?? resultStartDate,
        firstDate: DateTime(2000),
        lastDate: DateTime(2101),
      );

      if (resultEndDate != null) {
        setState(() {
          endDate = resultEndDate;
          if (endDate!.isBefore(startDate!)) {
            endDate = startDate; // Ensure end date is after start date
          }
        });
      }
    }
  }

  // Using CustomCalendarPicker for date range selection
  void _showCustomCalendarPicker(BuildContext context) async {
    DateTime? start, end;
    await showCupertinoModalPopup<void>(
      context: context,
      builder: (context) {
        return Container(
          height: 300,
          child: CustomCalendarPicker(
            leftPadding: 8.0,
            rightPadding: 8.0,
            topPadding: 8.0,
            bottomPadding: 8.0,
            initSelectedDate: DateTime.now(),
            firstDate: DateTime(2000),
            lastDate: DateTime(2101),
            isLoop: true,
            rowHeight: 50.0,
            selectedTextStyle: TextStyle(color: Colors.blue, fontSize: 18),
            todayTextStyle: TextStyle(color: Colors.red, fontSize: 18),
            otherMonthDayTextStyle: TextStyle(color: Colors.grey),
            onDateChanged: (date, isSelected) {
              if (isSelected) {
                if (start == null) {
                  start = date;
                } else if (end == null && date.isAfter(start!)) {
                  end = date;
                } else if (date.isBefore(start!)) {
                  start = date;
                  end = null;
                }
              } else {
                if (date == start) {
                  start = null;
                } else if (date == end) {
                  end = null;
                }
              }
            },
            onConfirm: (dates) {
              Navigator.of(context).pop();
              setState(() {
                startDate = dates.first;
                endDate = dates.last;
              });
            },
          ),
        );
      },
    );
  }

  @override
  Widget buildCustomCalendarPickerButton(BuildContext context) {
    return ElevatedButton(
      onPressed: () {
        _showCustomCalendarPicker(context);
      },
      child: Text('Select Date Range with CustomCalendarPicker'),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Calendar Picker Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Selected Date Range:',
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(height: 20),
            Text(
              '${startDate != null ? startDate!.toLocal().toString() : 'Start Date'} - ${endDate != null ? endDate!.toLocal().toString() : 'End Date'}',
              style: TextStyle(fontSize: 18),
            ),
            SizedBox(height: 40),
            buildCustomCalendarPickerButton(context),
          ],
        ),
      ),
    );
  }
}

注意:上面的代码包含了两种选择日期范围的方法:

  1. 使用showDatePicker两次选择开始日期和结束日期(这是Flutter自带的方法)。
  2. 使用CustomCalendarPicker插件来选择日期范围。

为了简化示例,我合并了两个方法的代码,但在实际使用中,你可能只需要其中一种方法。

你可以根据实际需求调整UI和逻辑。希望这个示例能帮助你更好地理解和使用custom_calendar_picker插件。

回到顶部