1

I'm trying to find / understand a simple flutter concept. I have a form that contains a date picker, the date picker is a stateful widget and opens the select date menu when tapped. I would like it to also open when the user taps "next" on the keyboard (to go to the next field, which is the date picker).

...
TextFormField(
  ...
  textInputAction: TextInputAction.next,
  focusNode: _focusNodeItem,
  onFieldSubmitted: (value) {
    _focusNodeItem.unfocus();
    // TODO: open datePicker from here
  },
  ...
),
DatePicker(
  date: _reminder.expires,
  selectDate: (date) {
    setState(() {
      _reminder =
          _reminder.copy(expires: date.toString());
    });
  },
)
...

Datepicker widget is something like this:

class DatePicker extends StatefulWidget {
  final String date;
  final ValueChanged<DateTime> selectDate;

  DatePicker({Key key, this.date, this.selectDate}) : super(key: key);

  @override
  _DatePickerState createState() => _DatePickerState();
}

class _DatePickerState extends State<DatePicker> {
...
void openDatePicker() {
    showCupertinoModalPopup<void>(
      context: context,
      builder: (BuildContext context) {
        return _buildBottomPicker(
          CupertinoDatePicker(
            mode: CupertinoDatePickerMode.date,
            initialDateTime: date,
            onDateTimeChanged: (DateTime newDateTime) {
              setState(() {
                date = newDateTime;
                widget.selectDate(newDateTime);
              });
            },
          ),
        );
      },
    );
  }
...
}

I get that widgets should not "mess" with each other, but what about simple cases like this?

Is there a simple (and correct) way to call openDatePicker() from the parent widget?

H4CKY
  • 564
  • 4
  • 12
  • Maybe `openDatePicker` shouldn't be inside the actual DatePicker. I don't know your code, but seems like moving this method to the form widget would make more sense. This way you would be able to call it, while keeping the DatePicker specific code separated (the `_buildBottomPicker` part). – Vinicius Braz Pinto Dec 24 '18 at 23:12
  • `openDatePicker` changes the state of the datePicker by showing the actual select date menu, moving it outside the `DatePicker` widget is a nono. – H4CKY Dec 25 '18 at 16:20
  • try with callbacks functions or streams, https://stackoverflow.com/a/51798698/2863386 – Shyju M Dec 27 '18 at 14:59
  • I already use callbacks to propagate the selected date to the parent widget (to the form): `final ValueChanged selectDate;` BUT i need to do this the other way around too, from the form I need to call `openDatePicker()`. – H4CKY Dec 27 '18 at 16:45

0 Answers0