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

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

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

date_time_picker 是一个用于在Flutter中显示日期或时间选择对话框的文本输入框组件。该组件扩展了 TextField,具有与 TextFormField 类似的功能。

使用方法

添加依赖

首先,在你的 pubspec.yaml 文件中添加 date_time_picker 依赖:

dependencies:
  ...
  date_time_picker: "^2.1.0"

导入包

然后在你的 Dart 文件中导入该包:

import 'package:date_time_picker/date_time_picker.dart';

示例代码

下面是一个完整的示例 Demo,展示了如何使用 date_time_picker 插件的不同类型和配置选项。

完整示例

import 'package:date_time_picker/date_time_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:intl/intl.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter DateTimePicker Demo',
      home: MyHomePage(),
      localizationsDelegates: [
        GlobalWidgetsLocalizations.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: [Locale('en', 'US')], //, Locale('pt', 'BR')],
    );
  }
}

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

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

class _MyHomePageState extends State<MyHomePage> {
  GlobalKey<FormState> _oFormKey = GlobalKey<FormState>();
  late TextEditingController _controller1;
  late TextEditingController _controller2;
  late TextEditingController _controller3;
  late TextEditingController _controller4;

  String _valueChanged1 = '';
  String _valueToValidate1 = '';
  String _valueSaved1 = '';
  String _valueChanged2 = '';
  String _valueToValidate2 = '';
  String _valueSaved2 = '';
  String _valueChanged3 = '';
  String _valueToValidate3 = '';
  String _valueSaved3 = '';
  String _valueChanged4 = '';
  String _valueToValidate4 = '';
  String _valueSaved4 = '';

  @override
  void initState() {
    super.initState();
    Intl.defaultLocale = 'pt_BR';
    _controller1 = TextEditingController(text: DateTime.now().toString());
    _controller2 = TextEditingController(text: DateTime.now().toString());
    _controller3 = TextEditingController(text: DateTime.now().toString());

    String lsHour = TimeOfDay.now().hour.toString().padLeft(2, '0');
    String lsMinute = TimeOfDay.now().minute.toString().padLeft(2, '0');
    _controller4 = TextEditingController(text: '$lsHour:$lsMinute');

    _getValue();
  }

  /// 模拟从数据库或API加载数据的行为
  Future<void> _getValue() async {
    await Future.delayed(const Duration(seconds: 3), () {
      setState(() {
        _controller1.text = '2000-09-20 14:30';
        _controller2.text = '2001-10-21 15:31';
        _controller3.text = '2002-11-22';
        _controller4.text = '17:01';
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter DateTimePicker Demo'),
      ),
      body: SingleChildScrollView(
        padding: EdgeInsets.only(left: 20, right: 20, top: 10),
        child: Form(
          key: _oFormKey,
          child: Column(
            children: <Widget>[
              DateTimePicker(
                type: DateTimePickerType.dateTimeSeparate,
                dateMask: 'd MMM, yyyy',
                controller: _controller1,
                firstDate: DateTime(2000),
                lastDate: DateTime(2100),
                icon: Icon(Icons.event),
                dateLabelText: 'Date',
                timeLabelText: "Hour",
                selectableDayPredicate: (date) {
                  if (date.weekday == 6 || date.weekday == 7) {
                    return false;
                  }
                  return true;
                },
                onChanged: (val) => setState(() => _valueChanged1 = val),
                validator: (val) {
                  setState(() => _valueToValidate1 = val ?? '');
                  return null;
                },
                onSaved: (val) => setState(() => _valueSaved1 = val ?? ''),
              ),
              DateTimePicker(
                type: DateTimePickerType.dateTime,
                dateMask: 'd MMMM, yyyy - hh:mm a',
                controller: _controller2,
                firstDate: DateTime(2000),
                lastDate: DateTime(2100),
                dateLabelText: 'Date Time',
                use24HourFormat: false,
                locale: Locale('en', 'US'),
                onChanged: (val) => setState(() => _valueChanged2 = val),
                validator: (val) {
                  setState(() => _valueToValidate2 = val ?? '');
                  return null;
                },
                onSaved: (val) => setState(() => _valueSaved2 = val ?? ''),
              ),
              DateTimePicker(
                type: DateTimePickerType.date,
                controller: _controller3,
                firstDate: DateTime(2000),
                lastDate: DateTime(2100),
                icon: Icon(Icons.event),
                dateLabelText: 'Date',
                locale: Locale('pt', 'BR'),
                onChanged: (val) => setState(() => _valueChanged3 = val),
                validator: (val) {
                  setState(() => _valueToValidate3 = val ?? '');
                  return null;
                },
                onSaved: (val) => setState(() => _valueSaved3 = val ?? ''),
              ),
              DateTimePicker(
                type: DateTimePickerType.time,
                initialValue: '',
                icon: Icon(Icons.access_time),
                timeLabelText: "Time",
                use24HourFormat: false,
                locale: Locale('pt', 'BR'),
                onChanged: (val) => setState(() => _valueChanged4 = val),
                validator: (val) {
                  setState(() => _valueToValidate4 = val ?? '');
                  return null;
                },
                onSaved: (val) => setState(() => _valueSaved4 = val ?? ''),
              ),
              SizedBox(height: 20),
              Text(
                'DateTimePicker data value onChanged:',
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
              SizedBox(height: 10),
              SelectableText(_valueChanged1),
              SelectableText(_valueChanged2),
              SelectableText(_valueChanged3),
              SelectableText(_valueChanged4),
              SizedBox(height: 10),
              ElevatedButton(
                onPressed: () {
                  final loForm = _oFormKey.currentState;

                  if (loForm?.validate() == true) {
                    loForm?.save();
                  }
                },
                child: Text('Submit'),
              ),
              SizedBox(height: 30),
              Text(
                'DateTimePicker data value validator:',
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
              SizedBox(height: 10),
              SelectableText(_valueToValidate1),
              SelectableText(_valueToValidate2),
              SelectableText(_valueToValidate3),
              SelectableText(_valueToValidate4),
              SizedBox(height: 10),
              Text(
                'DateTimePicker data value onSaved:',
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
              SizedBox(height: 10),
              SelectableText(_valueSaved1),
              SelectableText(_valueSaved2),
              SelectableText(_valueSaved3),
              SelectableText(_valueSaved4),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: () {
                  final loForm = _oFormKey.currentState;
                  loForm?.reset();

                  setState(() {
                    _valueChanged1 = '';
                    _valueChanged2 = '';
                    _valueChanged3 = '';
                    _valueChanged4 = '';
                    _valueToValidate1 = '';
                    _valueToValidate2 = '';
                    _valueToValidate3 = '';
                    _valueToValidate4 = '';
                    _valueSaved1 = '';
                    _valueSaved2 = '';
                    _valueSaved3 = '';
                    _valueSaved4 = '';
                  });

                  _controller1.clear();
                  _controller2.clear();
                  _controller3.clear();
                  _controller4.clear();
                },
                child: Text('Reset'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

关键点解释

  • type: 可以设置为 DateTimePickerType.date, DateTimePickerType.time, DateTimePickerType.dateTime, 或 DateTimePickerType.dateTimeSeparated
  • initialValue: 初始值可以是空字符串、null 或者一个有效的 DateTime 字符串。
  • firstDatelastDate: 设置可选日期范围。
  • icon: 显示在输入框前的图标。
  • dateLabelTexttimeLabelText: 设置日期和时间标签文本。
  • onChanged, validator, onSaved: 分别处理用户更改值、验证值和保存值时的操作。

通过上述示例,你可以轻松地在Flutter应用中集成日期和时间选择器,并根据需要进行自定义配置。


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

1 回复

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


当然,以下是一个关于如何在Flutter应用中使用date_time_picker插件的示例代码。这个插件允许你轻松地在应用中实现日期和时间的选择功能。

首先,确保你已经在pubspec.yaml文件中添加了date_time_picker依赖项(注意:实际上Flutter官方推荐使用的是showDatePickershowTimePicker,但这里假设你指的是一个自定义的或第三方实现的日期时间选择器插件,通常名字可能略有不同,这里以flutter_datetime_picker为例):

dependencies:
  flutter:
    sdk: flutter
  flutter_datetime_picker: ^2.0.0  # 请检查最新版本号

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

接下来,在你的Dart文件中,你可以按照以下方式使用flutter_datetime_picker插件:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'DateTime Picker 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('DateTime Picker Example'),
      ),
      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: () async {
                final DateTime picked = await DatePicker.showDateTimePicker(
                  context,
                  initialValue: selectedDateTime ?? DateTime.now(),
                  firstDate: DateTime(2000),
                  lastDate: DateTime(2101),
                  locale: Localizations.localeOf(context),
                );
                if (picked != null && picked != selectedDateTime) {
                  setState(() {
                    selectedDateTime = picked;
                  });
                }
              },
              child: Text('Select Date and Time'),
            ),
          ],
        ),
      ),
    );
  }
}

在这个示例中,我们创建了一个简单的Flutter应用,其中包含一个按钮,用于显示日期和时间选择器。当用户点击按钮时,会弹出一个日期和时间选择器对话框,用户可以选择一个日期和时间。选择完成后,选中的日期和时间会显示在按钮下方的文本中。

这个示例使用了flutter_datetime_picker插件的DatePicker.showDateTimePicker方法来显示日期和时间选择器。你可以根据需要调整initialValuefirstDatelastDate等参数来限制用户的选择范围。

请注意,由于插件和Flutter框架可能会不断更新,因此在实际使用中,请查阅最新的插件文档和Flutter官方文档以确保代码的正确性和兼容性。

回到顶部