This Flutter cookbook entry shows validating a text field:
TextFormField(
// The validator receives the text that the user has entered.
validator: (value) {
if (value.isEmpty) {
return 'Please enter some text';
}
return null;
},
);
However, it doesn't work with a DateTimefield
: The getter 'isEmpty' isn't defined for the type 'DateTime'.
Comparing to null
works nicely:
DateTimeField(
format: "MM-dd-yyyy",
controller: _dateController,
onShowPicker: (context, currentValue) {
return showDatePicker(
context: context,
firstDate: DateTime(1900),
initialDate: currentValue ?? DateTime.now(),
lastDate: DateTime(2100));
},
validator: (value) {
if (value == null) {
return 'Please enter a date';
}
return null;
},
onChanged: (value) {
},
)
HOWEVER, putting this code in an edit widget somehow fails because value
is null AT FIRST no matter what the widget is showing:
If I pick a date, which calls onChanged
, the value is not null, and everything validates.
But .. how to validate an existing field? Why is value
on the screen, but not set for the validator?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…