0

1.This is first code :

 DateTime? _selectedTime;
  void _datePicker(BuildContext con2) {
    showDatePicker(
      initialDate: DateTime.utc(2021, 12, 21),
      firstDate: DateTime(2000),
      lastDate: DateTime.now(),
      context: con2,
      // ignore: non_constant_identifier_names
    ).then((UserSelect) {
      if (UserSelect == null) {
        return;
      }
      setState(() {
        UserSelect = _selectedTime;
      });
    });
  }

2.this is second :

body: Container(
          color: Colors.black,
          height: double.infinity,
          child: Center(
            child: ElevatedButton(
              onPressed: () {
                _datePicker(context);
              },
              style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.all(Colors.purple)),
              child: Text(
                '${DateFormat('yyyy/MM/dd').format(_selectedTime!)}',
Siddharth Agrawal
  • 2,960
  • 3
  • 16
  • 37

2 Answers2

0

I don't think you are using it properly. showDatePicker returns a Future value. Check this out, maybe this will guide you; What is the correct way to add date picker in flutter app?

davidn
  • 378
  • 4
  • 12
0

you have many mistake the first mistake you make DateTime suport null-safty but .form, initialDate, firstDate and lastDate are not using null Saftey. The second mistake your _datePicker not support async because when the user select the time their need some time until select .

  DateTime _selectedTime = DateTime.now();
  void _datePicker(BuildContext con2) async {
    final DateTime? picked = await showDatePicker(
      context: con2,
      initialDate: DateTime.utc(2021, 12, 1), // Refer step 1
      firstDate: DateTime(2000),
      lastDate: DateTime.now(),
    ).then((UserSelect) {
      if (UserSelect == null) {
        return;
      }
      setState(() {
         _selectedTime = UserSelect;
      });
    });
  }

the third mistake you add ! in _seletedTime

ElevatedButton(
            onPressed: () => _datePicker(context)
            ,
            child: Text(
              '${DateFormat('yyyy/MM/dd').format(_selectedTime)}',),