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?
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.
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;
});
});
This is the screenshot of dialog box where i want to update new date after picked up.
This is what i tried in controller.dart.
class AppointmentController extends GetxController {
String t;
var selectedDate = DateTime.now().obs;
var selectedTime = TimeOfDay.now().obs;
void selectDate() async {
final DateTime pickedDate = await showDatePicker(
context: Get.context,
initialDate: selectedDate.value,
firstDate: DateTime(2018),
lastDate: DateTime(2025),
);
if (pickedDate != null && pickedDate != selectedDate.value) {
selectedDate.value = pickedDate;
}
}
This is what I tried in homepage.dart
Obx(
()=>TextFormField(
onTap:(){
controller.selectDate();
},
initialValue:DateFormat('DD-MM-
yyyy').format(controller.selectedDate.value).toString(),
),
add a TextEditingController to the textformfield and change text with this controller
class AppointmentController extends GetxController {
String t;
var selectedDate = DateTime.now().obs;
var selectedTime = TimeOfDay.now().obs;
TextEditingController textEditingController=TextEditingController();
void selectDate() async {
final DateTime pickedDate = await showDatePicker(
context: Get.context,
initialDate: selectedDate.value,
firstDate: DateTime(2018),
lastDate: DateTime(2025),
);
if (pickedDate != null && pickedDate != selectedDate.value) {
selectedDate.value = pickedDate;
textEditingController.text=DateFormat('DD-MM-
yyyy').format(selectedDate.value).toString();
}
}
Obx(
()=>TextFormField(
controller:controller.textEditingController,
onTap:(){
controller.selectDate();
},
initialValue:DateFormat('DD-MM-
yyyy').format(DateTime.now()).toString(),
),
This is the code i use to show time picker
var selectedTime;
void initState() {
super.initState();
selectedDate = DateTime.now();
selectedTime = TimeOfDay(hour: 23, minute: 23);
}
_selectTime(BuildContext context) async {
final TimeOfDay? picked = await showTimePicker(
context: context,
initialTime: selectedTime,
);
if(picked != null && picked != selectedTime)
setState(() {
selectedTime = picked;
});
}
This is the code i used to send data to another screen
SizedBox(width: 120,
child: ElevatedButton(
child: Text('Continue'),
onPressed: (){
widget.book.selectedDate = selectedDate;
widget.book.selectedTime= selectedTime;
Navigator.push(context, MaterialPageRoute(builder: (context)=> NewBookFinishView(book: widget.book)),
);
},
),
)
but when i press continue to send the value of date and time i get an error
TimeOfDay' is not a subtype of type 'DateTime? please help.
You try to assign twice your widget.book.selectedDate inside your onPressed (you might have used the wrong variable):
widget.book.selectedDate = selectedDate; // 1st assign with a DateTime
widget.book.selectedDate = selectedTime; // 2nd assign with a TimeOfDay
And even if your selectedDate is a dynamic with the 1st assignation being a DateTime you won't be able to assign the value of selectedTime as it is of type TimeOfDay.
I have this code of time picker, then I want to set the initial Time from a DateTime variable:
Future<Null> _selectTime(BuildContext context) async {
final TimeOfDay pickedS = await showTimePicker(
context: context,
initialTime: createdAt,
builder: (BuildContext context, Widget child) {
return MediaQuery(
data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: false),
child: child,
);});
if (pickedS != null && pickedS != selectedTime )
setState(() {
selectedTime = pickedS;
myTweets[actualTweetIndex].createdAt = dateFormat.format(selectedDate.toLocal()) +' ${selectedTime.hour}:${selectedTime.minute}:00 +0000 '+ selectedDate.year.toString();
});
}
The TimeOfDay class have a dedicated constructor for that :
TimeOfDay.fromDateTime(DateTime time)
You can check the documentation here
I have two separate buttons, one to select a date and one to select a time. How am I able to select both the date and then time by only having a single button?
For example, one the click of a "Schedule" button, a Datepicker will popup. Once the user selects a date and clicks "OK" in the Datepicker, the Timepicker will be called or popup.
This is the code for my time and date button widgets:
DateTime _date = new DateTime.now();
TimeOfDay _time = new TimeOfDay.now();
Future<Null> _selectDate(BuildContext context) async {
final DateTime picked = await showDatePicker(
context: context,
initialDate: _date,
firstDate: new DateTime(2019),
lastDate: new DateTime(2021),
);
if(picked != null && picked != _date) {
print('Date selected: ${_date.toString()}');
setState((){
_date = picked;
});
}
}
Future<Null> _selectTime(BuildContext context) async {
final TimeOfDay picked = await showTimePicker(
context: context,
initialTime: _time,
);
if(picked != null && picked != _time) {
print('Time selected: ${_time.toString()}');
setState((){
_time = picked;
});
}
}
Widgets:
final buttonRow = new Wrap(children: <Widget>[
new RaisedButton(
child: new Text('Select Date'),
onPressed: (){_selectDate(context);}
),
new RaisedButton(
child: new Text('Select Time'),
onPressed: (){_selectTime(context);}
)
]);
RaisedButton(
child: new Text('Select Date and Time'),
onPressed: (){ _selectDateAndTime(context); }
)
/* ... */
Future<Null> _selectDateAndTime(BuildContext context) async {
await _selectDate(context);
await _selectTime(context);
}