Skip to content

Commit c437326

Browse files
authored
[material_ui] Support custom date input formatters via CalendarDelegate (#12608)
This PR adds the `keyboardInputFormatters` method to `CalendarDelegate`. Previously, date input was strictly coupled to `MaterialLocalizations`. This change allows developers to provide a list of `TextInputFormatter`s via a custom `CalendarDelegate` to enforce specific input masks (e.g., dd/MM/yyyy) or restrict character entry in date pickers (`showDatePicker`, `showDateRangePicker`, and `InputDatePickerFormField`). Fixes flutter/flutter#83302 Fixes flutter/flutter#97134 Fixes flutter/flutter#62401 Fixes flutter/flutter#181043 Fixes flutter/flutter#115151 Fixes flutter/flutter#191639 Fixes partially flutter/flutter#150611 Port of flutter/flutter#181105 ## Pre-Review Checklist **Note**: The Flutter team is currently trialing the use of [Gemini Code Assist for GitHub](https://developers.google.com/gemini-code-assist/docs/review-github-code). Comments from the `gemini-code-assist` bot should not be taken as authoritative feedback from the Flutter team. If you find its comments useful you can update your code accordingly, but if you are unsure or disagree with the feedback, please feel free to wait for a Flutter team member's review for guidance on which automated comments should be addressed. [^1]: Regular contributors who have demonstrated familiarity with the repository guidelines only need to comment if the PR is not auto-exempted by repo tooling.
1 parent b8e9cf2 commit c437326

7 files changed

Lines changed: 529 additions & 0 deletions

File tree

Lines changed: 301 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,301 @@
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+
}
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
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_test/flutter_test.dart';
6+
import 'package:material_ui/material_ui.dart';
7+
import 'package:material_ui_examples/date_picker/show_date_picker.2.dart'
8+
as example;
9+
10+
void main() {
11+
testWidgets(
12+
'renders selected date text according to formatType and separator (input mode)',
13+
(WidgetTester tester) async {
14+
await tester.pumpWidget(
15+
const MaterialApp(home: example.DatePickerSample()),
16+
);
17+
18+
expect(find.text('No date selected'), findsOneWidget);
19+
20+
// Open date picker.
21+
await tester.tap(find.byType(OutlinedButton));
22+
await tester.pumpAndSettle();
23+
24+
final Finder textField = find.byType(TextField);
25+
expect(textField, findsOneWidget);
26+
27+
// Enter date: 30/07/2021.
28+
await tester.enterText(textField, '30072021');
29+
await tester.pump();
30+
31+
await tester.tap(find.text('OK'));
32+
await tester.pumpAndSettle();
33+
34+
expect(find.text('30.07.2021'), findsOneWidget);
35+
36+
// Change format to monthDayYear.
37+
await tester.tap(
38+
find.byType(DropdownButtonFormField<example.DateInputFormat>),
39+
);
40+
await tester.pumpAndSettle();
41+
await tester.tap(find.text('mm/dd/yyyy').last);
42+
await tester.pumpAndSettle();
43+
44+
expect(find.text('07.30.2021'), findsOneWidget);
45+
46+
// Change separator to dash.
47+
await tester.tap(
48+
find.byType(DropdownButtonFormField<example.DateSeparator>),
49+
);
50+
await tester.pumpAndSettle();
51+
await tester.tap(find.text('-').last);
52+
await tester.pumpAndSettle();
53+
54+
expect(find.text('07-30-2021'), findsOneWidget);
55+
56+
// Change format to yearMonthDay.
57+
await tester.tap(
58+
find.byType(DropdownButtonFormField<example.DateInputFormat>),
59+
);
60+
await tester.pumpAndSettle();
61+
await tester.tap(find.text('yyyy/mm/dd').last);
62+
await tester.pumpAndSettle();
63+
64+
expect(find.text('2021-07-30'), findsOneWidget);
65+
},
66+
);
67+
}

‎packages/material_ui/lib/src/date.dart‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,12 @@
44

55
/// @docImport 'calendar_date_picker.dart';
66
/// @docImport 'date_picker.dart';
7+
/// @docImport 'input_date_picker_form_field.dart';
78
/// @docImport 'text_field.dart';
89
library;
910

1011
import 'package:flutter/foundation.dart';
12+
import 'package:flutter/services.dart';
1113
import 'package:flutter/widgets.dart';
1214

1315
import 'material_localizations.dart';
@@ -158,6 +160,15 @@ abstract class CalendarDelegate<T extends DateTime> {
158160
/// The help text used on an empty [InputDatePickerFormField] to indicate
159161
/// to the user the date format being asked for.
160162
String dateHelpText(MaterialLocalizations localizations);
163+
164+
/// Optional list of [TextInputFormatter]s applied to the date input field.
165+
///
166+
/// These formatters control and restrict how the user enters text, such as
167+
/// enforcing a specific date mask.
168+
///
169+
/// The functionality of date input and validation relies on consistency between
170+
/// these formatters and the [parseCompactDate] method.
171+
List<TextInputFormatter>? keyboardInputFormatters(MaterialLocalizations localizations) => null;
161172
}
162173

163174
/// A [CalendarDelegate] implementation for the Gregorian calendar system.

0 commit comments

Comments
 (0)