can't get the date picked from my datepicker though i didn't getting error on my code.
Future selectDate() async {
DateTime picked = await showDatePicker(
context: context,
initialDate: new DateTime.now(),
firstDate: new DateTime(2016),
lastDate: new DateTime(2222));
if (picked != null) setState(() => picked = datepicked);
else{
print(picked);
}
}
}
You need to pass the context in the datepicker method. Complete working code below:
body: Center(
child: RaisedButton(
child: Text('click'),
onPressed: () {
selectDate(context);
}
)
),
Future selectDate(BuildContext context) async {
DateTime picked = await showDatePicker(
context: context,
initialDate: selectedDate,
firstDate: new DateTime(2016),
lastDate: new DateTime(2222));
if (picked != null && picked!= selectedDate) {
setState(() => selectedDate = picked);
print(picked);
}
else{
print(picked);
}
}
// 2020-02-21 00:00:00.000
Related
I am calculating pregnancy weeks .but the set state only update on second click.
ElevatedButton (
onPressed: () {
setState(() {
_selectDate(context);
sDate = selectedDate;
dueDate = sDate.add(Duration(days: DAYS_IN_PREGNANCY));
DateTime today = DateTime.now();
remaining = today.difference(dueDate).inDays.abs();
daysIn = DAYS_IN_PREGNANCY - remaining;
weekPart = daysIn % 7;
weekValue = daysIn / 7;
week = weekValue + "." + weekPart;
});
},
child: const Text("Choose Date"),
),
_selectDate(BuildContext context) async {
final DateTime? selected = await showDatePicker(
context: context,
initialDate: selectedDate,
firstDate: DateTime(2010),
lastDate: DateTime(2025),
);
setState(() {});
selectedDate = selected!;
}
As you can see, your _selectDate function is async and you need to await for it and also you don't need to call setState inside _selectDate, so change you click to this:
ElevatedButton (
onPressed: () async{ //<--- add this
var result = await _selectDate(context); //<--- add this
if(result != null){ //<--- add this
setState(() {
sDate = result; //<--- add this
dueDate = sDate.add(Duration(days: DAYS_IN_PREGNANCY));
DateTime today = DateTime.now();
remaining = today.difference(dueDate).inDays.abs();
daysIn = DAYS_IN_PREGNANCY - remaining;
weekPart = daysIn % 7;
weekValue = daysIn / 7;
week = weekValue + "." + weekPart;
});
}
},
child: const Text("Choose Date"),
),
and change your _selectDate to this:
DateTime? _selectDate(BuildContext context) async {
final DateTime? selected = await showDatePicker(
context: context,
initialDate: selectedDate,
firstDate: DateTime(2010),
lastDate: DateTime(2025),
);
return selected;
}
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(),
),
I want to implement a reminder feature in my application which reminds the user to do a particular task at a selected time. I have implemented a showDatePicker widget to select the date and month but i am unsure on how to display a showTimePicker after a date is selected in the showDatePicker
Could i get a suggestion on how this can be implemented?
code which displays the showDatePicker:
_selectDate() async {
final DateTime picker =await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2010),
lastDate: DateTime(2040)
);
if (picker != null) {
print(picker);
_daysPageController.jumpToDay(picker);
// Navigator.pop(context);
// print(selectedDate);
// await runJump(selectedDate);
// return selectedDate;
}
}
It is very simple, it creates a single function that in sequence calls the methods showDatePicker() and 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
}
}
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);
}