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
Bellow s the error i got when i tried to call
onPressed: () => selectedDateAndTime!.selectDayAndTimeL(),
what should i do from here?