Reputation: 1
I'm trying to integrate different date formats across screens based on user preferences,
Flutter's showDatePicker
function has an input field with which user can enter a text.
I want to specifically change the default showDatePicker
input format according to the selected date format.
This should include handling dateformat validations.
I was able to change the format to by passing different Locale
,
and also apply format validations
Locale('en', 'GB')
for DD/MM/YYYY
Locale('en', 'US')
(default) for MM/DD/YYYY
I want to know which Locale supports YYYY/MM/DD format
Upvotes: 0
Views: 178
Reputation: 1531
Flutter directly doesn't support YYYY/MM/DD format, You need to write your custom way to get it by using
Intl
plugin.
This is the way you can integrate it,
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(MaterialApp(
home: MyApp(),
));
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
TextEditingController dateController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Devraj Sample POC'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextFormField(
controller: dateController,
decoration: InputDecoration(
labelText: 'Enter date (YYYY/MM/DD)',
hintText: 'YYYY/MM/DD',
border: const OutlineInputBorder(),
),
keyboardType: TextInputType.number,
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
LengthLimitingTextInputFormatter(10),
DateTextInputFormatter(),
],
),
],
),
),
);
}
}
class DateTextInputFormatter extends TextInputFormatter {
@override
TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
String text = newValue.text;
// Remove any non-digit characters
text = text.replaceAll(RegExp(r'[^0-9]'), '');
// Format as YYYY/MM/DD
if (text.length > 4 && text[4] != '/') {
text = '${text.substring(0, 4)}/${text.substring(4)}';
}
if (text.length > 7 && text[7] != '/') {
text = '${text.substring(0, 7)}/${text.substring(7)}';
}
if (text.length > 10) {
text = text.substring(0, 10);
}
return TextEditingValue(
text: text,
selection: TextSelection.collapsed(offset: text.length),
);
}
}
Upvotes: 1