Flutter日期时间选择插件date_picker_timetable的使用

Flutter日期时间选择插件date_picker_timetable的使用

简介

date_picker_timetable 是一个基于 date_picker_timeline 的 Fork,由 Vivek Kaushik 和其他贡献者维护。它提供了更新的依赖项和一些从原始项目合并的 Pull Request。该插件允许用户在 Flutter 应用中选择日期和时间。

Demo

如何使用

  1. 导入包 在你的 Dart 文件中导入 date_picker_timetable 包:

    import 'package:date_picker_timetable/date_picker_timetable.dart';
    
  2. 使用 DatePicker 小部件

    下面是一个完整的示例代码,展示了如何在 Flutter 应用中使用 date_picker_timetable 插件。这个示例包括了 DatePickerMonthPickerYearPickerTimeline 三个小部件的使用。

完整示例代码

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(title: 'Date Picker Table Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, this.title}) : super(key: key);
  final String? title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  DatePickerController _controller = DatePickerController();

  DateTime _selectedDayValue = DateTime.now();
  DateTime _selectedMonthValue = DateTime.now();

  @override
  void initState() {
    super.initState();
  }

  // 获取某个月的总天数
  int daysInMonth(DateTime date) {
    var firstDayThisMonth = firstDayOfMonth(date);
    var firstDayNextMonth = DateTime(date.year, date.month + 1, 1);

    return firstDayNextMonth.difference(firstDayThisMonth).inDays;
  }

  // 获取某个月的第一天
  DateTime firstDayOfMonth(DateTime date) {
    return DateTime(date.year, date.month, 1);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.replay),
        onPressed: () {
          _controller.animateToSelection(); // 动画回到选中的日期
        },
      ),
      body: Container(
        padding: EdgeInsets.all(20.0),
        color: Colors.blueGrey[100],
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text("您选择的月份:"),
            Padding(padding: EdgeInsets.all(10)),
            Text(_selectedMonthValue.toString()),
            Padding(padding: EdgeInsets.all(20)),
            Text("您选择的日期:"),
            Padding(padding: EdgeInsets.all(10)),
            Text(_selectedDayValue.toString()),
            Padding(padding: EdgeInsets.all(20)),

            // 月份选择器
            Container(
              child: MonthPicker(
                startDate: DateTime.now(),
                height: 90,
                initialSelectedDate: _selectedMonthValue,
                selectionColor: Colors.black,
                selectedTextColor: Colors.white,
                borderRadius: BorderRadius.circular(16),
                onDateChange: (date) {
                  // 选择新的月份
                  setState(() {
                    _selectedMonthValue = date;
                  });
                },
              ),
            ),

            // 日期选择器
            Container(
              child: DatePicker(
                firstDayOfMonth(_selectedMonthValue), // 当前选择月份的第一天
                width: 60,
                height: 90,
                controller: _controller,
                initialSelectedDate: _selectedDayValue,
                selectionColor: Colors.black,
                selectedTextColor: Colors.white,
                daysCount: daysInMonth(_selectedMonthValue), // 当前月份的总天数
                inactiveDates: [
                  DateTime.now().add(Duration(days: 3)), // 3天后的日期不可选
                  DateTime.now().add(Duration(days: 4)), // 4天后的日期不可选
                  DateTime.now().add(Duration(days: 7)), // 7天后的日期不可选
                ],
                onDateChange: (date) {
                  // 选择新的日期
                  setState(() {
                    _selectedDayValue = date;
                  });
                },
              ),
            ),

            // 年份选择器
            Container(
              child: YearPickerTimeline(
                startDate: DateTime.now(),
                yearCount: 10, // 显示接下来10年的年份
                height: 90,
                width: 70,
                initialSelectedDate: _selectedMonthValue,
                selectionColor: Colors.black,
                selectedTextColor: Colors.white,
                borderRadius: BorderRadius.circular(12),
                onDateChange: (date) {
                  // 选择新的年份
                  setState(() {
                    _selectedMonthValue = date;
                  });
                },
              ),
            )
          ],
        ),
      ),
    );
  }
}

构造函数参数说明

DatePicker 的构造函数参数如下:

DatePicker(
  this.startDate, {  // 起始日期
  Key key,
  this.width,        // 日期选择器的宽度
  this.height,       // 日期选择器的高度
  this.controller,   // 用于控制日期选择器的控制器
  this.monthTextStyle,  // 月份文本样式
  this.dayTextStyle,    // 星期文本样式
  this.dateTextStyle,   // 日期文本样式
  this.selectedTextColor,  // 选中日期的文本颜色
  this.selectionColor,     // 选中日期的背景颜色
  this.deactivatedColor,   // 不可选日期的颜色
  this.initialSelectedDate,  // 初始选中的日期
  this.activeDates,         // 可选日期列表
  this.inactiveDates,       // 不可选日期列表
  this.daysCount,           // 显示的总天数
  this.onDateChange,        // 日期变化时的回调函数
  this.locale = "en_US",    // 语言设置,默认为英语
}) : super(key: key);

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

1 回复

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


当然,下面是一个关于如何在Flutter中使用date_picker_timetable插件的代码案例。这个插件允许用户选择一个日期和时间,非常适合需要精细时间选择的场景。

首先,你需要在你的pubspec.yaml文件中添加这个插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  date_picker_timetable: ^最新版本号  # 请替换为实际的最新版本号

然后,运行flutter pub get来获取这个依赖。

接下来,你可以在你的Flutter项目中使用这个插件。以下是一个简单的示例,展示如何集成和使用date_picker_timetable插件:

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

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

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

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  DateTime? selectedDateTime;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Date Picker Timetable Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              selectedDateTime == null
                  ? 'No date selected'
                  : 'Selected Date and Time: ${selectedDateTime!.toLocal()}',
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () => _selectDateTime(context),
              child: Text('Select Date and Time'),
            ),
          ],
        ),
      ),
    );
  }

  void _selectDateTime(BuildContext context) async {
    final DateTime? result = await showDatePickerTimetable(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime(DateTime.now().year - 1),
      lastDate: DateTime(DateTime.now().year + 1),
      timeInterval: 30, // 设置时间间隔,单位为分钟
      locale: Localizations.localeOf(context).languageCode,
      onConfirm: (dateTime) {
        setState(() {
          selectedDateTime = dateTime;
        });
      },
      onCancel: () {
        // 取消选择时的处理
      },
    );
  }
}

在这个示例中,我们创建了一个简单的Flutter应用,它有一个按钮,用户点击按钮后会弹出一个日期时间选择器。用户可以选择一个日期和时间,选择完成后,选择的日期和时间会显示在屏幕上。

代码解释:

  1. 添加依赖:在pubspec.yaml文件中添加date_picker_timetable插件的依赖。
  2. 导入插件:在需要使用插件的文件顶部导入date_picker_timetable
  3. 创建UI:使用MaterialAppScaffold创建了一个简单的UI,包含一个文本显示选择的日期时间和一个按钮。
  4. 选择日期时间:使用showDatePickerTimetable函数弹出一个日期时间选择器。这个函数是date_picker_timetable插件提供的,它允许你配置很多参数,如初始日期、可选的日期范围、时间间隔等。
  5. 处理选择结果:用户选择日期时间后,通过onConfirm回调处理选择结果,并将选择的日期时间保存在selectedDateTime变量中。

这样,你就成功地在Flutter项目中集成了date_picker_timetable插件,并实现了日期时间选择的功能。

回到顶部