Flutter自定义日期时间选择器插件datetime_picker_custom_qk的使用

Flutter 自定义日期时间选择器插件 datetime_picker_custom_qk 的使用

文档

日期时间 日期选择器 时间选择器 日期对话框

示例应用

使用

Padding(
  padding: const EdgeInsets.all(16.0),
  child: picker.InputDateTimePicker(
    isDiaLog: false,
    controller: _dateController,
    minDate: DateTime(2018, 1, 1),
    decoration: const InputDecoration(
      labelText: '输入自定义底部日期',
      hintText: '输入自定义底部日期',
      suffixIcon: Icon(Icons.calendar_today),
    ),
    onConfirm: (date) {
      _dateController.text = date.toString();
      print('确认 $date');
    },
    locale: picker.LocaleType.vi,
  ),
)

完整示例代码

import 'dart:developer';

import 'package:datetime_picker_custom_qk/datetime_picker_custom_qk.dart' as picker;
import 'package:flutter/material.dart';

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

class CustomPicker extends picker.CommonPickerModel {
  String digits(int value, int length) {
    return '$value'.padLeft(length, "0");
  }

  CustomPicker({DateTime? currentTime, super.locale}) {
    this.currentTime = currentTime ?? DateTime.now();
    setLeftIndex(this.currentTime.hour);
    setMiddleIndex(this.currentTime.minute);
    setRightIndex(this.currentTime.second);
  }

  [@override](/user/override)
  String? leftStringAtIndex(int index) {
    if (index >= 0 && index < 24) {
      return digits(index, 2); // 返回小时,格式化为两位数
    } else {
      return null;
    }
  }

  [@override](/user/override)
  String? middleStringAtIndex(int index) {
    if (index >= 0 && index < 60) {
      return digits(index, 2); // 返回分钟,格式化为两位数
    } else {
      return null;
    }
  }

  [@override](/user/override)
  String? rightStringAtIndex(int index) {
    if (index >= 0 && index < 60) {
      return digits(index, 2); // 返回秒,格式化为两位数
    } else {
      return null;
    }
  }

  [@override](/user/override)
  String leftDivider() {
    return "|"; // 左侧分隔符
  }

  [@override](/user/override)
  String rightDivider() {
    return "|"; // 右侧分隔符
  }

  [@override](/user/override)
  List<int> layoutProportions() {
    return [1, 2, 1]; // 设置布局比例
  }

  [@override](/user/override)
  DateTime finalTime() {
    return currentTime.isUtc
        ? DateTime.utc(currentTime.year, currentTime.month, currentTime.day,
            currentLeftIndex(), currentMiddleIndex(), currentRightIndex())
        : DateTime(currentTime.year, currentTime.month, currentTime.day,
            currentLeftIndex(), currentMiddleIndex(), currentRightIndex());
  }
}

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Flutter Demo',
      home: HomePage(),
    );
  }
}

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

  [@override](/user/override)
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final TextEditingController _dateController = TextEditingController();
  final TextEditingController _dateControllerInput = TextEditingController();
  final TextEditingController _dateControllerYear = TextEditingController();

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('日期时间选择器'),
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: picker.InputDateTimePicker(
              isDiaLog: false,
              controller: _dateControllerInput,
              minDate: DateTime(2018, 1, 1),
              decoration: const InputDecoration(
                labelText: '输入自定义底部日期',
                hintText: '输入自定义底部日期',
                suffixIcon: Icon(Icons.calendar_today),
              ),
              onConfirm: (date) {
                _dateControllerInput.text = date.toString();
                log('确认测试 $date');
              },
              locale: picker.LocaleType.vi,
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: picker.InputDateTimePicker(
              isDiaLog: false,
              isYear: true,
              controller: _dateControllerYear,
              minDate: DateTime(2018, 1, 1),
              decoration: const InputDecoration(
                labelText: '输入自定义底部年份',
                hintText: '输入自定义底部年份',
                suffixIcon: Icon(Icons.calendar_today),
              ),
              onConfirm: (date) {
                _dateControllerYear.text = date.year.toString();
                log('确认测试 $date');
              },
              locale: picker.LocaleType.vi,
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: TextField(
              controller: _dateController,
              decoration: const InputDecoration(
                labelText: '输入自定义对话框日期',
                hintText: '输入自定义对话框日期',
                suffixIcon: Icon(Icons.calendar_today),
              ),
              readOnly: true,
              onTap: () {
                picker.DatePicker.showDatePicker(
                  context,
                  isDiaLog: true,
                  showTitleActions: true,
                  minTime: DateTime(2018, 3, 5),
                  onChanged: (date) {
                    log('更改 $date 在时区 ${date.timeZoneOffset.inHours}');
                  },
                  onConfirm: (date) {
                    _dateController.text =
                        '${date.day}-${date.month}-${date.year}';
                    log('确认 $date');
                  },
                  currentTime: DateTime.now(),
                  locale: picker.LocaleType.vi,
                );
              },
            ),
          ),
          TextButton(
            onPressed: () {
              picker.DatePicker.showDatePicker(context,
                  showTitleActions: true,
                  minTime: DateTime(2018, 3, 5),
                  onChanged: (date) {
                    log('更改 $date 在时区 ${date.timeZoneOffset.inHours}');
                  },
                  onConfirm: (date) {
                    log('确认 $date');
                  },
                  currentTime: DateTime.now(),
                  locale: picker.LocaleType.vi);
            },
            child: const Text(
              '显示日期',
              style: TextStyle(color: Colors.black),
            ),
          ),
          TextButton(
            onPressed: () {
              picker.DatePicker.showTimePicker(context,
                  showTitleActions: true,
                  onChanged: (date) {
                    log('更改 $date 在时区 ${date.timeZoneOffset.inHours}');
                  },
                  onConfirm: (date) {
                    log('确认 $date');
                  },
                  currentTime: DateTime.now());
            },
            child: const Text(
              '显示时间',
              style: TextStyle(color: Colors.black),
            ),
          ),
          TextButton(
            onPressed: () {
              picker.DatePicker.showTime12hPicker(context,
                  showTitleActions: true,
                  onChanged: (date) {
                    log('更改 $date 在时区 ${date.timeZoneOffset.inHours}');
                  },
                  onConfirm: (date) {
                    log('确认 $date');
                  },
                  currentTime: DateTime.now());
            },
            child: const Text(
              '显示12小时制时间选择器(AM/PM)',
              style: TextStyle(color: Colors.black),
            ),
          ),
          TextButton(
            onPressed: () {
              picker.DatePicker.showDateTimePicker(context,
                  showTitleActions: true,
                  minTime: DateTime(2020, 5, 5, 20, 50),
                  maxTime: DateTime(2020, 6, 7, 05, 09),
                  onChanged: (date) {
                    log('更改 $date 在时区 ${date.timeZoneOffset.inHours}');
                  },
                  onConfirm: (date) {
                    log('确认 $date');
                  },
                  locale: picker.LocaleType.vi);
            },
            child: const Text(
              '显示日期时间选择器',
              style: TextStyle(color: Colors.black),
            ),
          ),
          TextButton(
            onPressed: () {
              picker.DatePicker.showDateTimePicker(context,
                  showTitleActions: true,
                  onChanged: (date) {
                    log('更改 $date 在时区 ${date.timeZoneOffset.inHours}');
                  },
                  onConfirm: (date) {
                    log('确认 $date');
                  },
                  currentTime: DateTime.utc(2019, 12, 31, 23, 12, 34),
                  locale: picker.LocaleType.vi);
            },
            child: const Text(
              '显示UTC(越南)日期时间选择器',
              style: TextStyle(color: Colors.black),
            ),
          ),
        ],
      ),
    );
  }
}

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

1 回复

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


当然,下面是一个关于如何在Flutter中使用datetime_picker_custom_qk插件的示例代码。这个插件允许你自定义日期和时间选择器。首先,你需要在你的pubspec.yaml文件中添加该插件的依赖:

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

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

接下来,你可以在你的Dart文件中使用DateTimePickerCustom组件。以下是一个完整的示例代码,展示了如何在一个简单的Flutter应用中集成并使用这个自定义日期时间选择器:

import 'package:flutter/material.dart';
import 'package:datetime_picker_custom_qk/datetime_picker_custom.dart';

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

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

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

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

  void _selectDateTime() async {
    DateTime? dateTime = await showDateTimePickerCustom(
      context: context,
      locale: Localizations.localeOf(context),
      initialDate: selectedDateTime ?? DateTime.now(),
      firstDate: DateTime(2000),
      lastDate: DateTime(2101),
      dateFormat: 'yyyy-MM-dd',
      timeFormat: 'HH:mm',
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8.0),
      ),
      headerDecoration: BoxDecoration(
        color: Colors.blue,
      ),
      headerTextStyle: TextStyle(color: Colors.white),
      bodyTextStyle: TextStyle(color: Colors.black),
      cancelTextStyle: TextStyle(color: Colors.grey),
      confirmTextStyle: TextStyle(color: Colors.blue),
      cancelText: 'Cancel',
      confirmText: 'Confirm',
      is24HourFormat: true,
    );

    if (dateTime != null && dateTime != selectedDateTime) {
      setState(() {
        selectedDateTime = dateTime;
      });
    }
  }

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

在这个示例中:

  1. 我们首先添加了datetime_picker_custom_qk作为依赖。
  2. 创建了一个MyAppMyHomePage小部件。
  3. _MyHomePageState中,我们定义了一个selectedDateTime变量来存储用户选择的日期和时间。
  4. 使用showDateTimePickerCustom函数显示自定义的日期和时间选择器。
  5. 根据用户的选择更新selectedDateTime变量,并刷新UI。

你可以根据需要调整showDateTimePickerCustom的参数,以满足你的自定义需求。

回到顶部