Flutter: How to call a Future function when on pressed

Issue

i am trying to Implement show Time picker after a Date has been selected… i was able to implement the showDatePicker and it was working fine… then i tried to implement the ShowTime picker by following a fix from here "StackOverFlow" but after putting the code in my project i noticed that when i click on the iconButton which was supposed to call the showDatePicker Nothing happens

i pasted the codes bellow
the commented code bellow is the ShowDateicker i was using till i wanted to implement the ShowTimePicker

Future _selectDayAndTime(BuildContext context) async {
    DateTime _selectedDay = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(2018),
        lastDate: DateTime(2030),
        builder: (BuildContext context, Widget child) => child);

    TimeOfDay _selectedTime = await showTimePicker(
      context: context,
      initialTime: TimeOfDay.now(),
    );

    if (_selectedDay != null && _selectedTime != null) {
      //a little check
    }
    setState(() {
      _selectedDate = _selectedDay;
    });
    print('...');
  }

  // void _presentDatePicker() {
  //   showDatePicker(
  //           context: context,
  //           initialDate: DateTime.now(),
  //           firstDate: DateTime.now(),
  //           lastDate: DateTime(2050))
  //       .then((pickedDate) {
  //     if (pickedDate == null) {
  //       return;
  //     }
  //     setState(() {
  //       _selectedDate = pickedDate;
  //     });
  //   });
  //   print('...');
  // }

then the Icon Button code bellow

FlatButton(
                                      textColor: Theme.of(context).primaryColor,
                                      child: Icon(Icons.calendar_today),
                                      onPressed: () => _selectDayAndTime,
                                    ),

Link to the fix i was trying to follow

Solution

i later read and understand how to call the function… I was doing it right but missed something check the code down below

FlatButton(
                                      textColor: 
Theme.of(context).primaryColor,
                                      child: Icon(Icons.calendar_today),
                                      onPressed: () => 
_selectDayAndTime(context), // I forgot to add the 
(context) and that's what fixed the issue for me
                                    ),

Now everything is working perfectly

Answered By – Britchi3

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *