Ale
Ale

Reputation: 2344

Flutter Widget return value in a custom callback

I've created my own Widget which consists in a DatePicker, here the code:

class DatePicker extends StatelessWidget {
  final Icon icon;
  final DateTime initialDate;
  final ValueChanged<DateTime> onDateSelected;

  DatePicker({this.icon = const Icon(Icons.date_range), @required this.initialDate, this.onDateSelected});

  Future<Null> _selectDate(BuildContext context) async {
    final DateTime picked = await showDatePicker(context: context, initialDate: initialDate, firstDate: DateTime(2015, 8), lastDate: DateTime(2101));
    if (picked != null && picked != initialDate) {
      // TODO: return the picked value in the 'OnDateSelect' callback
      print(picked.toString());
    }
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: <Widget>[
        Text(initialDate.toString()),
        IconButton(
          icon: this.icon,
          onPressed: () => _selectDate(context),
        )
      ],
    );
  }
}

I want to use it like this:

DatePicker(
      initialDate: _ticketDate,
      onDateSelected: (newDate) {
        print(newDate);
      },
    );

What I don't know is how to return the date selected in my custom onDateSelected callback once the Future<Null> _selectDate has been executed.

Any ideas?

Upvotes: 2

Views: 2465

Answers (1)

Benjamin
Benjamin

Reputation: 6161

It's very simple:

All you do is call the function provided by the widget and provide the parameter, in this case, the picked date.

  Future<void> _selectDate(BuildContext context) async {
    final DateTime picked = await showDatePicker(
        context: context,
        initialDate: initialDate,
        firstDate: DateTime(2015, 8),
        lastDate: DateTime(2101));
    if (picked != null && picked != initialDate) {
      onDateSelected(picked); // just do this
    }
  }

Upvotes: 1

Related Questions