Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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:

screenshot of date field

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
989 views
Welcome To Ask or Share your Answers For Others

1 Answer

等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...