在flutter应用程序中添加日期选择器的正确方法是什么?

Cod*_*ter 35 android ios flutter dart-2 flutter-layout

在我的应用中,我正在创建注册页面,我需要在其中添加DOB。我想在其中添加日期选择器,但我没有正确的方法来执行此操作。

che*_*ins 76

一个简单的应用程序,展示其用法:

import 'dart:async';

import 'package:flutter/material.dart';

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

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

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  DateTime selectedDate = DateTime.now();

  Future<Null> _selectDate(BuildContext context) async {
    final DateTime picked = await showDatePicker(
        context: context,
        initialDate: selectedDate,
        firstDate: DateTime(2015, 8),
        lastDate: DateTime(2101));
    if (picked != null && picked != selectedDate)
      setState(() {
        selectedDate = picked;
      });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Text("${selectedDate.toLocal()}"),
            SizedBox(height: 20.0,),
            RaisedButton(
              onPressed: () => _selectDate(context),
              child: Text('Select date'),
            ),
          ],
        ),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 完毕。飞镖板已创建;) (4认同)
  • 您可以使用年、月和日期创建自己的版本,也可以使用以下 `Text("${selectedDate.toLocal()}".split(' ')[0]),` (2认同)

Del*_*ain 12

更新:可重用小部件: 首先创建一个单独的小部件,如下所示(使用 date_time_picker 包):

class CustomDateTimePicker extends StatelessWidget {

  CustomDateTimePicker({super.key, this.labelText, this.hintText, this.onValidate, this.onSaved});

  final String? labelText;
  final String? hintText;
  final String? Function(String?)? onValidate;
  final Function(String?)? onSaved;

  @override
  Widget build(BuildContext context) {
    return DateTimePicker(
      dateLabelText: labelText,
      fieldHintText: hintText,
      firstDate: DateTime(1995),
      lastDate: DateTime.now().add(Duration(days: 365)),
      validator: onValidate,
      onSaved: onSaved,
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

然后按如下方式使用这个小部件:

CustomDateTimePicker(
    hintText: 'Select Blood Donate Date',
    onValidate: (value) {
    return Validate.requiredField(
        value!, 'This is field is required');
      },
    onSaved: (value) {
    controller.donateDate.value = value!;
   },
 )
Run Code Online (Sandbox Code Playgroud)

注意验证类如下:

class Validate {
  static String? requiredField(String value, String message) {
    if (value.trim().isEmpty) {
      return message;
    }
    return null;
  }
}
Run Code Online (Sandbox Code Playgroud)

首先,您需要创建一个变量。在该变量中,您可以按如下方式存储所选日期:

import 'package:flutter/material.dart';
import 'package:intl/intl.dart'; //this is an external package for formatting date and time

class DatePicker extends StatefulWidget {
  @override
  _DatePickerState createState() => _DatePickerState();
}

class _DatePickerState extends State<DatePicker> {
  DateTime _selectedDate;

  //Method for showing the date picker
  void _pickDateDialog() {
    showDatePicker(
            context: context,
            initialDate: DateTime.now(),
            //which date will display when user open the picker
            firstDate: DateTime(1950),
            //what will be the previous supported year in picker
            lastDate: DateTime
                .now()) //what will be the up to supported date in picker
        .then((pickedDate) {
      //then usually do the future job
      if (pickedDate == null) {
        //if user tap cancel then this function will stop
        return;
      }
      setState(() {
        //for rebuilding the ui
        _selectedDate = pickedDate;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        RaisedButton(child: Text('Add Date'), onPressed: _pickDateDialog),
        SizedBox(height: 20),
        Text(_selectedDate == null //ternary expression to check if date is null
            ? 'No date was chosen!'
            : 'Picked Date: ${DateFormat.yMMMd().format(_selectedDate)}'),
      ],
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

第二个选项: 可以通过使用https://pub.dev/packages/date_time_picker这个库来使用另一个选项。您可以在小部件树中使用此库,并将选择的日期或时间存储在变量中作为字符串:

首先,将包添加到 pubspec.yaml 中,然后点击获取包。下面只给出了一个日期选择演示,详细的实现可以在给定的包url中找到。

import 'package:flutter/material.dart';

import 'package:date_time_picker/date_time_picker.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Date Time'),
    );
  }
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  String _selectedDate;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(10.0),
              child: DateTimePicker(
                initialValue: '', // initialValue or controller.text can be null, empty or a DateTime string otherwise it will throw an error.
                type: DateTimePickerType.date,
                dateLabelText: 'Select Date',
                firstDate: DateTime(1995),
                lastDate: DateTime.now()
                    .add(Duration(days: 365)), // This will add one year from current date
                validator: (value) {
                  return null;
                },
                onChanged: (value) {
                  if (value.isNotEmpty) {
                    setState(() {
                    _selectedDate = value;
                    });
                  }
                },
                // We can also use onSaved
                onSaved: (value) {
                  if (value.isNotEmpty) {
                    _selectedDate = value;
                  }
                },
              ),
            ),
            SizedBox(height: 16),
            Text(
              'Your Selected Date: $_selectedDate',
              style: TextStyle(fontSize: 16),
            ),
          ],
        ),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)


use*_*234 10

对于时间选择器-

在类级别声明此变量

TimeOfDay selectedTime =TimeOfDay.now();
Run Code Online (Sandbox Code Playgroud)

并调用此方法:-

Future<Null> _selectTime(BuildContext context) async {
    final TimeOfDay picked_s = await showTimePicker(
        context: context,
        initialTime: selectedTime, builder: (BuildContext context, Widget child) {
           return MediaQuery(
             data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: false),
            child: child,
          );});

    if (picked_s != null && picked_s != selectedTime )
      setState(() {
        selectedTime = picked_s;
      });
  }
Run Code Online (Sandbox Code Playgroud)


Ana*_*afi 8

简单的方法是使用CupertinoDatePicker类:

首先导入它在颤振中构建的包:

import 'package:flutter/cupertino.dart';
Run Code Online (Sandbox Code Playgroud)

然后只需在您的表单中添加此小部件:

            Container(
              height: 200,
              child: CupertinoDatePicker(
                mode: CupertinoDatePickerMode.date,
                initialDateTime: DateTime(1969, 1, 1),
                onDateTimeChanged: (DateTime newDateTime) {
                  // Do something
                },
              ),
            ),
Run Code Online (Sandbox Code Playgroud)

结果将如下图所示:

带有 CupertinoDatePicker 的日期选择器

您也可以将模式更改为 (dateAndTime,time)... 例如对于 dateAndTime 模式:

            Container(
              height: 200,
              child: CupertinoDatePicker(
                mode: CupertinoDatePickerMode.dateAndTime,
                initialDateTime: DateTime(1969, 1, 1, 11, 33),
                onDateTimeChanged: (DateTime newDateTime) {
                  //Do Some thing
                },
                use24hFormat: false,
                minuteInterval: 1,
              ),
            ),
Run Code Online (Sandbox Code Playgroud)

结果将如下图所示:

日期和时间示例


Piy*_*rya 5

Flutter提供showDatePicker了实现此目的的功能。它是Flutter材料库的一部分。

您可以在showDatePicker找到完整的文档。

您还可以在此处找到实现的示例:日期和时间选择器