How to validate DateTime so that end date cannot be before start date?


I made a custom widget that provide the value of a selected date, so I’ve been working with two textfield that have showDatePicker function (this is my custom widget), I tried use the paramater firstdate of the function showDatePicker as parameter to the second textfield that is the end date, so I need to validate that if user picked a start date then end date cannot be before to start date, the values of boths dates are asign to variables that I manage with provider. I recive the response as strings, then transform both value to compare with isBefore or isAfter.


class _DateFilterState extends State<_DateFilter> {
  final TextEditingController _textEditingController = TextEditingController();

  Widget build(BuildContext context) {
    return TextField(
      enableInteractiveSelection: false,
      decoration: InputDecoration(labelText: widget.title),
      focusNode: AlwaysDisabledFocusNode(),
      controller: _textEditingController,
      onTap: () {
        setState(() {});

  _selectDate(context) async {
    DateTime? selectedDate = await showDatePicker(
      context: context,
      initialDate: widget.initialDate,
      firstDate: widget.firstDate ?? DateTime(2015),
      lastDate: widget.lastDate ??,
    if (selectedDate != null) {
      _textEditingController.text = DateFormat('dd/MM/yyyy').format(selectedDate);

Validation end date

                children: [
                      child: _DateFilter(
                    onChanged: (value) => authsProvider.dateStart = value,
                    title: 'Start date',
                  const SizedBox(width: 10),
                      child: _DateFilter(
                    title: 'End date',
                    onChanged: (value) => authsProvider.dateEnd = value,
                    firstDate: provider.dateSelected =
                        provider.dateStart.isNotEmpty && formatter.parse(authsProvider.dateEnd).isAfter(formatter.parse(provider.dateStart))
                            ? formatter.parse(provider.dateStart)
                            : DateTime(2015),

Does anyone know how to validate correctly? I got confuse, I know that there’re other ways to make a better manage of range of date, but they are the requirements.


You should use DateTime.

DateTime dateStart =; //YOUR DATE GOES HERE
DateTime dateEnd =; // YOUR DATE GOES HERE
bool isValidDate = dateStart.isBefore(dateEnd);

Answered By – Dee S

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published