How to save the selected datetime from DateTimeField in Flutter
305
At First, Declare a Controller,
final TextEditingController _timeController = TextEditingController();
then pass it to the
DateTimeField
like this
DateTimeField(
controller: _timeController,
....
)
access it like _timeController.text
Or else DateTimeField
also offer onSaved
, to use this, first declare a variable var _time
and then pass it like this
DateTimeField(
onSaved: (val) => setState(() => _time = val),
....
)
Author by
Fathima Shafana
Updated on January 01, 2023Comments
-
Fathima Shafana over 1 year
I have used the below code to save the date time. It selects both date and time and displays the selected date and time in the textfield. But how do I save it in a variable or how do I save it in my database. I have 'note' table in database. I want to save the selected date and time in 'actn_on' column in 'note' table.
Text('Action on (${format.pattern})'), DateTimeField( format: format, onShowPicker: (context, currentValue) async { final date = await showDatePicker( context: context, firstDate: DateTime(1900), initialDate: currentValue ?? DateTime.now(), lastDate: DateTime(2100)); if (date != null) { final time = await showTimePicker( context: context, initialTime: TimeOfDay.fromDateTime(currentValue ?? DateTime.now()), ); return DateTimeField.combine(date, time); } else { return currentValue; } }, ),
-
Fathima Shafana over 2 yearsNo actually my value is in return DateTimeField.combine(date, time); right? I am trying all the methods to save it in a variable but to no avail.
-
Fathima Shafana over 2 yearsEven dt=currentValue shows the same error. to add a cast
-
Fathima Shafana over 2 yearsEven this is not working.
-
Fathima Shafana over 2 yearsI tried printing action where action=_datetimecontroller.text but it prints nothing
-
Fathima Shafana over 2 yearsThankyou it worked !! Sorry I was trying it wrong first. this is the right way --> note.actn_on=_datetimeController.text;
-
Kozubi over 2 yearscurrentValue - check type.
String dt
is just a proposition.