|
| 1 | +// Copyright 2013 The Flutter Authors |
| 2 | +// Use of this source code is governed by a BSD-style license that can be |
| 3 | +// found in the LICENSE file. |
| 4 | + |
| 5 | +import 'package:flutter/services.dart'; |
| 6 | +import 'package:material_ui/material_ui.dart'; |
| 7 | + |
| 8 | +/// Flutter code sample showing how to use [showDatePicker] with a custom |
| 9 | +/// [CalendarDelegate] and its [CustomDateInputDelegate.keyboardInputFormatters] to |
| 10 | +/// synchronize input masking with date parsing and validation. |
| 11 | +
|
| 12 | +void main() => runApp(const DatePickerSampleApp()); |
| 13 | + |
| 14 | +class DatePickerSampleApp extends StatelessWidget { |
| 15 | + const DatePickerSampleApp({super.key}); |
| 16 | + |
| 17 | + @override |
| 18 | + Widget build(BuildContext context) { |
| 19 | + return const MaterialApp(home: DatePickerSample()); |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +class DatePickerSample extends StatefulWidget { |
| 24 | + const DatePickerSample({super.key}); |
| 25 | + |
| 26 | + @override |
| 27 | + State<DatePickerSample> createState() => _DatePickerSampleState(); |
| 28 | +} |
| 29 | + |
| 30 | +class _DatePickerSampleState extends State<DatePickerSample> { |
| 31 | + DateTime? _selectedDate; |
| 32 | + |
| 33 | + DateInputFormat _formatType = .dayMonthYear; |
| 34 | + DateSeparator _separator = .dot; |
| 35 | + |
| 36 | + Future<void> _showPicker() async { |
| 37 | + final CustomDateInputDelegate customDateInputDelegate = |
| 38 | + CustomDateInputDelegate(formatType: _formatType, separator: _separator); |
| 39 | + |
| 40 | + final DateTime? result = await showDatePicker( |
| 41 | + context: context, |
| 42 | + initialDate: _selectedDate ?? DateTime(2021, 7, 25), |
| 43 | + firstDate: DateTime(2021), |
| 44 | + lastDate: DateTime(2999, 7, 25), |
| 45 | + initialEntryMode: DatePickerEntryMode.input, |
| 46 | + calendarDelegate: customDateInputDelegate, |
| 47 | + ); |
| 48 | + |
| 49 | + if (result != null) { |
| 50 | + setState(() { |
| 51 | + _selectedDate = result; |
| 52 | + }); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + @override |
| 57 | + Widget build(BuildContext context) { |
| 58 | + final String label = _selectedDate == null |
| 59 | + ? 'No date selected' |
| 60 | + : DateInputFormatter( |
| 61 | + formatType: _formatType, |
| 62 | + separator: _separator.value, |
| 63 | + ).format(_selectedDate!); |
| 64 | + |
| 65 | + final content = <Widget>[ |
| 66 | + Text(label), |
| 67 | + const SizedBox(height: 24), |
| 68 | + DropdownButtonFormField<DateInputFormat>( |
| 69 | + initialValue: _formatType, |
| 70 | + decoration: const InputDecoration(labelText: 'Date format'), |
| 71 | + items: [ |
| 72 | + for (final format in DateInputFormat.values) |
| 73 | + DropdownMenuItem(value: format, child: Text(format.patternLabel)), |
| 74 | + ], |
| 75 | + onChanged: (DateInputFormat? value) { |
| 76 | + if (value != null) { |
| 77 | + setState(() => _formatType = value); |
| 78 | + } |
| 79 | + }, |
| 80 | + ), |
| 81 | + const SizedBox(height: 16), |
| 82 | + DropdownButtonFormField<DateSeparator>( |
| 83 | + initialValue: _separator, |
| 84 | + decoration: const InputDecoration(labelText: 'Separator'), |
| 85 | + items: [ |
| 86 | + for (final separator in DateSeparator.values) |
| 87 | + DropdownMenuItem(value: separator, child: Text(separator.value)), |
| 88 | + ], |
| 89 | + onChanged: (DateSeparator? value) { |
| 90 | + if (value != null) { |
| 91 | + setState(() => _separator = value); |
| 92 | + } |
| 93 | + }, |
| 94 | + ), |
| 95 | + const SizedBox(height: 24), |
| 96 | + OutlinedButton(onPressed: _showPicker, child: const Text('Select date')), |
| 97 | + ]; |
| 98 | + |
| 99 | + return Scaffold( |
| 100 | + appBar: AppBar(title: const Text('showDatePicker with input delegate')), |
| 101 | + body: Padding( |
| 102 | + padding: const EdgeInsets.all(16), |
| 103 | + child: Column(mainAxisSize: MainAxisSize.min, children: content), |
| 104 | + ), |
| 105 | + ); |
| 106 | + } |
| 107 | +} |
| 108 | + |
| 109 | +enum DateInputFormat { |
| 110 | + dayMonthYear(fieldLengths: [2, 2, 4], patternLabel: 'dd/mm/yyyy'), |
| 111 | + monthDayYear(fieldLengths: [2, 2, 4], patternLabel: 'mm/dd/yyyy'), |
| 112 | + yearMonthDay(fieldLengths: [4, 2, 2], patternLabel: 'yyyy/mm/dd'); |
| 113 | + |
| 114 | + const DateInputFormat({ |
| 115 | + required this.fieldLengths, |
| 116 | + required this.patternLabel, |
| 117 | + }); |
| 118 | + |
| 119 | + final List<int> fieldLengths; |
| 120 | + final String patternLabel; |
| 121 | + |
| 122 | + String pattern(String separator) => patternLabel.replaceAll('/', separator); |
| 123 | +} |
| 124 | + |
| 125 | +enum DateSeparator { |
| 126 | + slash('/'), |
| 127 | + dash('-'), |
| 128 | + dot('.'); |
| 129 | + |
| 130 | + const DateSeparator(this.value); |
| 131 | + final String value; |
| 132 | +} |
| 133 | + |
| 134 | +/// A [TextInputFormatter] used by the input mode of [showDatePicker] to |
| 135 | +/// format and validate date text according to a specific [DateInputFormat]. |
| 136 | +/// |
| 137 | +/// This formatter is intended to be used when [DatePickerEntryMode.input] |
| 138 | +/// is enabled, ensuring that the manual date entry matches the same format |
| 139 | +/// expected by the picker. |
| 140 | +/// |
| 141 | +/// It: |
| 142 | +/// - Restricts input to digits and automatically inserts the configured |
| 143 | +/// [separator]. |
| 144 | +/// - Enforces the field order defined by [DateInputFormat] |
| 145 | +/// (e.g. day–month–year, month–day–year, year–month–day). |
| 146 | +/// - Provides utilities to format a [DateTime] into a string and to parse |
| 147 | +/// user input back into a [DateTime], returning `null` for invalid values. |
| 148 | +class DateInputFormatter extends TextInputFormatter { |
| 149 | + const DateInputFormatter({required this.formatType, required this.separator}); |
| 150 | + |
| 151 | + final DateInputFormat formatType; |
| 152 | + final String separator; |
| 153 | + |
| 154 | + String get pattern => formatType.pattern(separator); |
| 155 | + |
| 156 | + String format(DateTime date) { |
| 157 | + final String day = date.day.toString().padLeft(2, '0'); |
| 158 | + final String month = date.month.toString().padLeft(2, '0'); |
| 159 | + final String year = date.year.toString().padLeft(4, '0'); |
| 160 | + |
| 161 | + final components = switch (formatType) { |
| 162 | + DateInputFormat.dayMonthYear => [day, month, year], |
| 163 | + DateInputFormat.monthDayYear => [month, day, year], |
| 164 | + DateInputFormat.yearMonthDay => [year, month, day], |
| 165 | + }; |
| 166 | + |
| 167 | + return components.join(separator); |
| 168 | + } |
| 169 | + |
| 170 | + DateTime? parse(String? input) { |
| 171 | + if (input == null || input.isEmpty) { |
| 172 | + return null; |
| 173 | + } |
| 174 | + |
| 175 | + final List<String> parts = input.split(separator); |
| 176 | + if (parts.length != 3) { |
| 177 | + return null; |
| 178 | + } |
| 179 | + |
| 180 | + final (String d, String m, String y) = switch (formatType) { |
| 181 | + DateInputFormat.dayMonthYear => (parts[0], parts[1], parts[2]), |
| 182 | + DateInputFormat.monthDayYear => (parts[1], parts[0], parts[2]), |
| 183 | + DateInputFormat.yearMonthDay => (parts[2], parts[1], parts[0]), |
| 184 | + }; |
| 185 | + |
| 186 | + final int? day = int.tryParse(d); |
| 187 | + final int? month = int.tryParse(m); |
| 188 | + final int? year = int.tryParse(y); |
| 189 | + |
| 190 | + if (day == null || month == null || year == null) { |
| 191 | + return null; |
| 192 | + } |
| 193 | + if (month < 1 || month > 12 || day < 1) { |
| 194 | + return null; |
| 195 | + } |
| 196 | + |
| 197 | + final int lastDayOfMonth = DateTime(year, month + 1, 0).day; |
| 198 | + if (day > lastDayOfMonth) { |
| 199 | + return null; |
| 200 | + } |
| 201 | + |
| 202 | + return DateTime(year, month, day); |
| 203 | + } |
| 204 | + |
| 205 | + @override |
| 206 | + TextEditingValue formatEditUpdate( |
| 207 | + TextEditingValue oldValue, |
| 208 | + TextEditingValue newValue, |
| 209 | + ) { |
| 210 | + final String digits = newValue.text.replaceAll(RegExp(r'\D'), ''); |
| 211 | + final int maxLength = formatType.fieldLengths.fold<int>(0, (a, b) => a + b); |
| 212 | + |
| 213 | + if (digits.length > maxLength) { |
| 214 | + return oldValue; |
| 215 | + } |
| 216 | + |
| 217 | + final String formatted = _applyMask(digits); |
| 218 | + |
| 219 | + int digitsBefore = _countDigits( |
| 220 | + newValue.text.substring(0, newValue.selection.baseOffset), |
| 221 | + ); |
| 222 | + |
| 223 | + final digitIndices = <int>[]; |
| 224 | + for (int i = 0; i < formatted.length; i++) { |
| 225 | + if (RegExp(r'\d').hasMatch(formatted[i])) digitIndices.add(i); |
| 226 | + } |
| 227 | + |
| 228 | + int newOffset = digitsBefore == 0 ? 0 : digitIndices[digitsBefore - 1] + 1; |
| 229 | + |
| 230 | + if (newOffset < formatted.length && formatted[newOffset] == separator) { |
| 231 | + newOffset++; |
| 232 | + } |
| 233 | + |
| 234 | + return TextEditingValue( |
| 235 | + text: formatted, |
| 236 | + selection: TextSelection.collapsed(offset: newOffset), |
| 237 | + ); |
| 238 | + } |
| 239 | + |
| 240 | + int _countDigits(String text) => text.replaceAll(RegExp(r'\D'), '').length; |
| 241 | + |
| 242 | + String _applyMask(String digits) { |
| 243 | + final StringBuffer buffer = StringBuffer(); |
| 244 | + int offset = 0; |
| 245 | + |
| 246 | + for ( |
| 247 | + int i = 0; |
| 248 | + i < formatType.fieldLengths.length && offset < digits.length; |
| 249 | + i++ |
| 250 | + ) { |
| 251 | + final int len = formatType.fieldLengths[i]; |
| 252 | + final int end = (offset + len).clamp(0, digits.length); |
| 253 | + buffer.write(digits.substring(offset, end)); |
| 254 | + offset = end; |
| 255 | + |
| 256 | + if (offset < digits.length && i < formatType.fieldLengths.length - 1) { |
| 257 | + buffer.write(separator); |
| 258 | + } |
| 259 | + } |
| 260 | + return buffer.toString(); |
| 261 | + } |
| 262 | +} |
| 263 | + |
| 264 | +final class CustomDateInputDelegate extends GregorianCalendarDelegate { |
| 265 | + const CustomDateInputDelegate({ |
| 266 | + required this.formatType, |
| 267 | + required this.separator, |
| 268 | + }); |
| 269 | + |
| 270 | + final DateInputFormat formatType; |
| 271 | + final DateSeparator separator; |
| 272 | + |
| 273 | + DateInputFormatter get _formatter => |
| 274 | + DateInputFormatter(formatType: formatType, separator: separator.value); |
| 275 | + |
| 276 | + @override |
| 277 | + List<TextInputFormatter>? keyboardInputFormatters( |
| 278 | + MaterialLocalizations localizations, |
| 279 | + ) { |
| 280 | + return <TextInputFormatter>[ |
| 281 | + FilteringTextInputFormatter.digitsOnly, |
| 282 | + _formatter, |
| 283 | + ]; |
| 284 | + } |
| 285 | + |
| 286 | + @override |
| 287 | + String dateHelpText(MaterialLocalizations localizations) => |
| 288 | + _formatter.pattern; |
| 289 | + |
| 290 | + @override |
| 291 | + String formatCompactDate( |
| 292 | + DateTime date, |
| 293 | + MaterialLocalizations localizations, |
| 294 | + ) => _formatter.format(date); |
| 295 | + |
| 296 | + @override |
| 297 | + DateTime? parseCompactDate( |
| 298 | + String? inputString, |
| 299 | + MaterialLocalizations localizations, |
| 300 | + ) => _formatter.parse(inputString); |
| 301 | +} |
0 commit comments