Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to set Date limit to 6 months from current date Flutter?

I need to set the calendar limit to next 6 months from now. the code i tried to run is given below:

Future<void> _selectDate(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
        context: context,
        initialDate: selectedDate,
        firstDate: DateTime.now(),
        lastDate: DateTime(DateTime.now().month + 6));
    if (picked != null && picked != selectedDate)
      setState(() {
        selectedDate = picked;
      });
  }

When i try to run this code i get the given error:

Unhandled Exception: 'package:flutter/src/material/date_picker.dart': Failed assertion: line 226 pos 5: '!lastDate.isBefore(firstDate)': lastDate 0008-01-01 00:00:00.000 must be on or after firstDate 2022-02-09 00:00:00.000.
E/flutter ( 1931): #0      _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:46:39)
E/flutter ( 1931): #1      _AssertionError._throwNew (dart:core-patch/errors_patch.dart:36:5)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

A clean way to add something to a DateTime is:

DateTime myDate = DateTime.now();
DateTime myDateWithSixMonthsAdded = myDate.add(Duration(days: 180));

Add 180 days since Duration does not have a months parameter.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading