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),
   ....
    )
Share:
305
Fathima Shafana
Author by

Fathima Shafana

Updated on January 01, 2023

Comments

  • Fathima Shafana
    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
    Fathima Shafana over 2 years
    No 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
    Fathima Shafana over 2 years
    Even dt=currentValue shows the same error. to add a cast
  • Fathima Shafana
    Fathima Shafana over 2 years
    Even this is not working.
  • Fathima Shafana
    Fathima Shafana over 2 years
    I tried printing action where action=_datetimecontroller.text but it prints nothing
  • Fathima Shafana
    Fathima Shafana over 2 years
    Thankyou it worked !! Sorry I was trying it wrong first. this is the right way --> note.actn_on=_datetimeController.text;
  • Kozubi
    Kozubi over 2 years
    currentValue - check type. String dt is just a proposition.