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

Time:02-11

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)

CodePudding user response:

Your lastDate input DateTime(DateTime.now().month 6)) is incorrect.

Since DateTime.now().month 6 will produce an int, DateTime(DateTime.now().month 6)) will be the year DateTime.now().month 6.

Change that line to:

lastDate: DateTime(DateTime.now().year, DateTime.now().month 6, DateTime.now().day));

Or use the .add function for DateTime class:

DateTime.now().add(const Duration(days: 180));

CodePudding user response:

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.

  • Related