Home > Back-end >  error : I get error ' Unexpected null value' when I run app
error : I get error ' Unexpected null value' when I run app

Time:12-20

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!)}',

CodePudding user response:

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?

CodePudding user response:

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)}',),
  • Related