In our daily development, there are many times when users need to select a date or enter a date. How do we do this with Flutter? We can use an existing widget, DatePicker, to fulfill this requirement.

1. Prepare a variable

DateTime selectedDate = datetime.now ();Copy the code

Set up the UI

/// Default is today Column(mainAxisSize: mainAxisSize. Min, children: <Widget>[ Text( "${selectedDate.toLocal()}".split(' ')[0], style: TextStyle(fontSize: 55, fontWeight: Fontweight.bold),), SizedBox(height: 20.0,), RaisedButton(onPressed: () => _selectDate(context), // Refer step 3 child: Text( 'Select date', style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold), ), color: Colors.greenAccent, ), ], )Copy the code

Write a method to call the showDatePicker function

_selectDate(BuildContext context) async { final DateTime picked = await showDatePicker( context: context, initialDate: selectedDate, // Refer step 1 firstDate: DateTime(2000), lastDate: DateTime(2025), ); if (picked ! = null && picked ! = selectedDate) setState(() { selectedDate = picked; }); }Copy the code

Complete the above steps to display a basic date picker component, isn’t it easy? Next we can do some customization:

1. How do I display only specific date ranges

ShowDatePicker (context: context, initialDate: selectedDate, firstDate: DateTime(2000), // Required lastDate: DateTime(2025), // Required )Copy the code

2. How do I display text fields instead of calendars

/ / / set initialEntryMode: DatePickerEntryMode. Input can be showDatePicker (context: context, initialDate: selectedDate, firstDate: DateTime(2000), lastDate: DateTime(2025), initialEntryMode: DatePickerEntryMode.input, )Copy the code

3. How do I display the year list first

///设置initialDatePickerMode: DatePickerMode.year即可
showDatePicker(
  context: context,
  initialDate: selectedDate,
  firstDate: DateTime(2000),
  lastDate: DateTime(2025),
  initialDatePickerMode: DatePickerMode.year,
)
Copy the code

4. How to allow users to enter a specific range of dates

Users can choose bool _decidetoenable (DateTime day) {if if the interval goes from the current date to add 10 days ((day.isAfter(DateTime.now().subtract(Duration(days: 1))) && day.isBefore(DateTime.now().add(Duration(days: 10))))) { return true; } return false; } showDatePicker( context: context, initialDate: selectedDate, firstDate: DateTime(2000), lastDate: DateTime(2025), selectableDayPredicate: _decideWhichDayToEnable, )Copy the code

5. How do I change the text

showDatePicker( context: context, initialDate: selectedDate, firstDate: DateTime(2000), lastDate: DateTime(2025), helpText: 'title ', cancelText:' cancel ', confirmText: 'confirm ',)Copy the code

6. How do I change the error message

ShowDatePicker (Context: context, initialDate: selectedDate, firstDate: DateTime(2000), lastDate: DateTime(2025), errorFormatText: 'Error ', errorInvalidText:' error ',)Copy the code

7. How do I change the input box label and prompt text

showDatePicker(
  context: context,
  initialDate: selectedDate,
  firstDate: DateTime(2000),
  lastDate: DateTime(2025),
  fieldLabelText: 'Booking date',
  fieldHintText: 'Month/Date/Year',
)
Copy the code

8. How to change the theme

showDatePicker( context: context, initialDate: selectedDate, firstDate: DateTime(2000), lastDate: DateTime(2025), builder: (context, child) { return Theme( data: ThemeData.light(), // This will change to light theme. child: child, ); },)Copy the code

The complete code is as follows:

import 'package:flutter/material.dart'; class DateApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData(primarySwatch: Colors.blue, brightness: Brightness.dark), home: DatePickerDemo(), ); } } class DatePickerDemo extends StatefulWidget { @override _DatePickerDemoState createState() => _DatePickerDemoState(); } class _DatePickerDemoState extends State<DatePickerDemo> { /// Which holds the selected date /// Defaults to today's date. DateTime selectedDate = DateTime.now(); Bool _decidetoenable (DateTime day) {/// Interval ranging from the current date to add 10 days users can choose if ((day.isAfter(DateTime.now().subtract(Duration(days: 1))) && day.isBefore(DateTime.now().add(Duration(days: 10))))) { return true; } return false; } _selectDate(BuildContext context) async { final DateTime picked = await showDatePicker( context: Context, initialDate: selectedDate, firstDate: DateTime(2000), lastDate: DateTime(2025), helpText: "calendar ", cancelText: "Cancel", confirmText: "sure," / / initialEntryMode: DatePickerEntryMode. Input, / / initialDatePickerMode: DatePickerMode.year, selectableDayPredicate: _decideWhichDayToEnable, builder: (context, child) { return Theme(data: ThemeData.light(), child: child); }); if (picked ! = null && picked ! = selectedDate) setState(() { selectedDate = picked; }); } @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ Text( "${selectedDate.toLocal()}".split(' ')[0], style: TextStyle(fontSize: 55, fontWeight: fontweight.bold),), SizedBox(height: 20.0,), RaisedButton(onPressed: () => _selectDate(context), child: Text( 'Select date', style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold), ), color: Colors.greenAccent, ), ], ), ), ); }}Copy the code