1

i have this funtion which handles my Date and Time picker widget ...Code bellow...

Future selectDayAndTimeL(BuildContext context) async {
    DateTime? selectedDay = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(2021),
        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(() {
      selectedDateAndTime = DateTime(
        selectedDay!.year,
        selectedDay!.month,
        selectedDay!.day,
        selectedTime!.hour,
        selectedTime!.minute,
      );
      // _selectedDate = _selectedDay;
    });
    // print('...');
  }

initially it was inside my add new task class/dart file "Stateful Widget", and everything was working fine but now i want to also use that function on the Home screen when a button is pressed.

Then i checked a StackOverflow question on how to call a function from another dart file which the solution required that i keep the Function on a different dart file then call it from there like this Example

void launchWebView () {
  print("1234");
} 

when i did i was getting an error which i lookedup and it was because of the "setState" in my function so i needed to put it inside a Stateful widget,

import 'package:flutter/material.dart';

class SelectDateAndTime extends StatefulWidget {
  @override
  _SelectDateAndTimeState createState() => _SelectDateAndTimeState();
}

class _SelectDateAndTimeState extends State<SelectDateAndTime> {

  DateTime? _selectedDate;
// DateTime _selectedDate;
  DateTime? selectedDateAndTime;

  Future selectDayAndTimeL(BuildContext context) async {
    DateTime? selectedDay = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(2021),
        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(() {
      selectedDateAndTime = DateTime(
        selectedDay!.year,
        selectedDay!.month,
        selectedDay!.day,
        selectedTime!.hour,
        selectedTime!.minute,
      );
      // _selectedDate = _selectedDay;
    });
    // print('...');
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    throw UnimplementedError();
  }
}

And that was the only difference from my code with the example i followed and i was still getting an error when i tried calling the funtion, and i have checked all the quetions related to clling functions from another dart file / class and none of them had SetState so their solution didn't work for me

This is the error i got when i called just the Function Name enter image description here Bellow s the error i got when i tried to call

onPressed: () => selectedDateAndTime!.selectDayAndTimeL(),

enter image description here

what should i do from here?

Britchi3
  • 180
  • 5
  • 17

2 Answers2

2

I'm guessing that you originally had a Statefull widget, that probably looked something like this:

class OriginalWidget extends StatefulWidget {
  @override
  _OriginalWidgetState createState() => _OriginalWidgetState();
}

class _OriginalWidgetState extends State<OriginalWidget> {

  DateTime? _selectedDate;
  DateTime? selectedDateAndTime;

  Future selectDayAndTimeL(BuildContext context) async {
    DateTime? selectedDay = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(2021),
        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(() {
      selectedDateAndTime = DateTime(
        selectedDay!.year,
        selectedDay!.month,
        selectedDay!.day,
        selectedTime!.hour,
        selectedTime!.minute,
      );
      // _selectedDate = _selectedDay;
    });
    // print('...');
  }

  @override
  Widget build(BuildContext context) {
    return FlatButton(
          onPressed: () => selectDayAndTimeL(context));
  } 
} 

Now, what you want to do is to reuse the logic of your selectDayAndTimeL function.

The problem is that both the selectedDateAndTime variable and the setState method are specific to the Statefull widget _OriginalWidgetState.

What you need to do is to modify your selectDayAndTimeL function so that it can take those widget-specific stuff as parameters.

So, in essence what you would do is:

1st create the function as a standalone function, for instance in a new dart file. Make sure to remove the widget-specific stuff from the body and leave them as parameters:

  Future selectDayAndTimeL(BuildContext context, void Function(DateTime) onDateAndTimeSelected) async {
    DateTime? selectedDay = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(2021),
        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
    }
    
      onDateAndTimeSelected(DateTime(
        selectedDay!.year,
        selectedDay!.month,
        selectedDay!.day,
        selectedTime!.hour,
        selectedTime!.minute,
      ));
    // print('...');
  }

2nd, on your new Statefull widgets, you may now call this function, make sure that you send the new onDateAndTimeSelected parameter:

class SecondWidget extends StatefulWidget {
  @override
  _SecondWidgetState createState() => _SecondWidgetState();
}

class _SecondWidgetState extends State<SecondWidget> {
  DateTime? selectedDateAndTime;

  @override
  Widget build(BuildContext context) {
    return FlatButton(
          onPressed: () => selectDayAndTimeL(context, 
        setState((DateTime selectedValue) {
             selectedDateAndTime = selectedValue;
         } ) 
    ));
  }  
} 

And then you could just follow the same logic for any other Statefull widget that needs to call your function.

Andres Silva
  • 874
  • 1
  • 7
  • 26
  • Please where is the "DateTime? ```selectedDateAndTime;``` " coming from? i was trying to use it then because i tried to put the funtion in a stateful widget named "SelectedDateAndTime" just as you mentioned in the first code snippet, but since we are taking the Stateful widget out and leaving the funtion as a standalone code which name is ```selectedDateAndTimeL``` does that mean i should replace the ```DateTime? selectedDateAndTime;``` with ```DateTime? selectedDateAndTimeL;``` ?... notice the difference is one of them ends with "L" and the other doesn't – Britchi3 Feb 07 '22 at 01:09
0

setState tells a stateful widget to re-render based on the changed data. In your case you are changing selectedDateAndTime and re-building the Widget with updated data.

If you want to update/rebuild a widget from a "remote" function you need to use a callback.

Future selectDayAndTimeL(BuildContext context,Function(DateTime time) onDateTimeSelected)  async {
    DateTime? selectedDay = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(2021),
        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
    }
    // call the callback here with your calculated data
    onDateTimeSelected(
      DateTime(
        selectedDay!.year,
        selectedDay!.month,
        selectedDay!.day,
        selectedTime!.hour,
        selectedTime!.minute,
      ),
    );
  }

Then in the StatefulWidget where you call this function:

selectDayAndTimeL(BuildContext context,(time) {
  setState(() {
    selectedDateAndTime = time;
  });
});
MindStudio
  • 706
  • 1
  • 4
  • 13
  • 1
    I should write this code on the onpressed? ```selectDayAndTimeL(BuildContext context,(time) { setState(() { selectedDateAndTime = time; }); });``` – Britchi3 Feb 06 '22 at 01:22