flutterdartflutter-widget

DatePicker on Flutter: null value on getting date piked :


can't get the date picked from my datepicker though i didn't getting error on my code.

  Future selectDate() async {
    DateTime picked = await showDatePicker(
        context: context,
        initialDate: new DateTime.now(),
        firstDate: new DateTime(2016),
        lastDate: new DateTime(2222));
    if (picked != null) setState(() => picked = datepicked);
    else{
      print(picked);
    }
  }
}

enter image description here


Solution

  • You need to pass the context in the datepicker method. Complete working code below:

    body: Center(
            child: TextButton(
            child: Text('click'),
            onPressed: () {
              selectDate(context);
              }
            )
          ),
    
    
    Future selectDate(BuildContext context) async {
        DateTime picked = await showDatePicker(
            context: context,
            initialDate: selectedDate,
            firstDate: new DateTime(2016),
            lastDate: new DateTime(2222));
        if (picked != null && picked!= selectedDate) {
          setState(() => selectedDate = picked);
          print(picked);
        }
        else{
          print(picked);
        }
      }
    

    Result:

    2020-02-21 00:00:00.000