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

Categories

0 votes
984 views
in Technique[技术] by (71.8m points)

How to validate a DateTimeField in Flutter?

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?


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

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...