Home > Mobile >  Can not Get Hour from showTimePicker Flutter
Can not Get Hour from showTimePicker Flutter

Time:11-01

ShowTimePicker is easy and understandable, but I don't know where this error came from.

The code:

TimeOfDay selectedTime = TimeOfDay.now();
    
    IconButton(icon: Icon(Icons.access_time, color: Colors.blue),
               onPressed: () async {
                                  TimeOfDay? _time = await showTimePicker(
                                    context: context,
                                    initialTime: TimeOfDay.now(),
                                  );
                                  if (_time != null) {
                                    selectedTime.hour = _time.hour;
                                  }
                                },
                              ),

The error shows under hour word in selectedTime.hour:

'hour' can't be used as a setter because it's final.  Try finding a different setter, or making 'hour' non-final.

CodePudding user response:

Use .replacing() method.

Returns a new TimeOfDay with the hour and/or minute replaced.

  onPressed: () async {
          TimeOfDay selectedTime = TimeOfDay.now();

          TimeOfDay? _time = await showTimePicker(
            context: context,
            initialTime: TimeOfDay.now(),
          );
          if (_time != null) {
            selectedTime = selectedTime.replacing(hour: _time.hour); // use setState if neended
          }

          print(selectedTime.toString());
        },

For more TimeOfDay-replacing

CodePudding user response:

Yes, if you go to definition of class TimeOfDay you'll see hour is final so you can reset this property. But you just reset selectedTime (both hour and minute will reset). Then in initialTime property you should check selectedTime and set like below code if it's not null. Each Time pick time you'll keep last value.

 onPressed: () async {
        TimeOfDay? _time = await showTimePicker(
          context: context,
          initialTime:
              selectedTime != null ? selectedTime : TimeOfDay.now(),
        );
        if (_time != null) {
          selectedTime = _time;
          // selectedTime.hour = _time.hour;
          print(selectedTime.hour);
        }
      },
  • Related