2

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?

1 Answer 1

1

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
    }
  }
Sign up to request clarification or add additional context in comments.

3 Comments

Stupid question, I don't know how I didn't see it...Thanks a lot!
It's not a stupid question, haha, plus this will help other people too. Just think about how you helped many others with the same issue.
@Ale not at all. we all are humans, even if have experience we may forget simple things.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.