Ayad
Ayad

Reputation: 691

Flutter - InputDatePickerFormField

I'm trying to add a text field that will get the date in the input field. I'm using InputDatePickerFormField widget. The issue I'm finding that it does not show error when the date is incorrect.

Here is my code:

class _BirthDay extends StatefulWidget {
  @override
  __BirthDayState createState() => __BirthDayState();
}

class __BirthDayState extends State<_BirthDay> {
  DateTime? selectedDate;

  @override
  Widget build(BuildContext context) {
    final firstDate = DateTime(DateTime.now().year - 120);
    final lastDate = DateTime.now();

    return InputDatePickerFormField(
      firstDate: firstDate,
      lastDate: lastDate,
      fieldLabelText: '${AppLocalizations.of(context)!.dateOfBirth}',
      errorFormatText: '${AppLocalizations.of(context)!.dateOfBirthInvalid}',
      errorInvalidText: '${AppLocalizations.of(context)!.dateOfBirthInvalid}',
      onDateSubmitted: (date) {
        print(date);
        setState(() {
          selectedDate = date;
        });
      },
      onDateSaved: (date) {
        print(date);
        setState(() {
          selectedDate = date;
        });
      },
    );
  }
}

Upvotes: 2

Views: 7884

Answers (2)

Oscar Caicedo
Oscar Caicedo

Reputation: 310

You need to save the form to see the validations errors

_formKey2.currentState.save();

You can call it on the submit button

Upvotes: 0

Omatt
Omatt

Reputation: 10483

One way that you can add a checker on your Text fields is by setting the fields as children of a Form. Using this, you'll be able to validate the values on your fields once submitted.

final _formKey = GlobalKey<FormState>();

...

Form(
  key: _formKey,
  child: InputDatePickerFormField(...),
)

Then you can run a check using _formKey.currentState!.validate()). Trigger this validation on any onClick or onPressed event.

Upvotes: 1

Related Questions