I am trying to use the DatePicker in flutter and I want to set the initialDate to DateTime.now() and the lastDate I want to set to DateTime.now() + 20yrs so it increments the year dynamically.
Current I have my lastDate set to the year (2100), but this would cause a problem when the year 2101 reaches. So how can I modify my function to increase the lastDate dynamically?
Here is my function:
DateTime _date = DateTime.now();
Future < Null > _checkInDate(BuildContext contex) async {
DateTime ? _datePicker = await showDatePicker(
context: context,
builder: (BuildContext context, Widget ? child) {
return Theme(
data: ThemeData(
primaryColor: Color(0xFFEF5350),
colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.red)
.copyWith(secondary: Color(0xFFFFF176)),
),
child: child ? ? Text(""),
);
},
initialDate: _date,
firstDate: DateTime.now(),
lastDate: DateTime(2100), //how can i increase the lastDate dynamically?
);
if (_datePicker != null && _datePicker != _date) {
_checkInController.text = DateFormat('dd-MM-yyyy').format(_datePicker);
}
}
Yes you can, use DateTime.now().year to get the current year and then add as many years as you want. Like this:
final date = DateTime(DateTime.now().year + 20);
Related
I have a Future (async) Date&Time picker function which works fine from within the body of my stateful widget which contains the "Builder" and the function can be called via the onpressed by just this:
onPressed: () {SelectDayAndTimeL();},
Code:
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('...');
}
Now I want to be able to call this function from different dart files/screens which means I have to keep this function on a different dart file which I have tried to do, but because of the setState in the function it needs to be inside a stateful widget. I have tried putting it inside a stateful widget but keeps getting errors.
class Picker extends StatefulWidget {
#override
_PickerState createState() => _PickerState();
}
class _PickerState extends State<Picker> {
#override
Future<Widget> build(BuildContext context) async { //the error in on the build on this line
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;
});
}
}
How do I properly place the Future Function inside a stateful widget and how to call it on an onpressed?
I don't know if the title I gave this question is actually what it's supposed to be, but I don't know how else to put it.
The whole setState inside your method is the problem. Your method should do one thing: get a date and time from the user. And there it's responsibility ends.
Future<DateTime> 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
}
return DateTime(
_selectedDay.year,
_selectedDay.month,
_selectedDay.day,
_selectedTime.hour,
_selectedTime.minute,
);
}
Now your onPressed becomes:
onPressed: () async {
final pickedDatetime = await SelectDayAndTimeL(context);
setState(() { selectedDateAndTime = pickedDatetime });
},
You have sucessfully divided your code into the function that picks a thing and your widget, which updates after the thing is picked.
The function that picks the date and time can now be reused in every other widget.
Create a function which will take datetime as a parameter and setstate of the stateful widget. Write this inside the stateful widget. Pass this function to the other class as an argument. Once the date is picked call this method by passing the datetime selected.
You should pass the setState function itself as a parameter to the method. This way, inside the method you will always be using the correct state setter function. That is especially necessary since you need to keep the variables _selectedDay etc inside the widget, not on the static method. Try this:
Future selectDayAndTimeL(BuildContext context, Function(DateTime) dateTimeSetter) async { //add a function to receive and use the
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
}
// Create the variable with the picked date
DateTime selectedDateAndTime = DateTime(
_selectedDay.year,
_selectedDay.month,
_selectedDay.day,
_selectedTime.hour,
_selectedTime.minute,
);
//call the function from the parameter, which will be executed on the calling widget
dateTimeSetter(selectedDateAndTime);
....
}
Then, call your function to show the datetime picker passing the context, and a function that receives a DateTime parameter, which will be the parameter picked by the user. When the user picks a date, this function body will be executed, calling setState and setting the pickedTime variable.
class Picker extends StatefulWidget {
DateTime pickedTime;
#override
_PickerState createState() => _PickerState();
}
class _PickerState extends State<Picker> {
#override
Future<Widget> build(BuildContext context) async {
return ...
_selectDayAndTimeL(context, (DateTime time){
setState((){
widget.pickedTime = time;
});
});
...
You can also extract the function from the parameter into a normal named function, and just use its name in the parameter, but I'll leave it as is for now to make it simpler.
Also, don't forget to make your method public and static if necessary for the scope of your code.
i have this date picker in my app, and i want the last date to be 3 years ago from the time using the app how can i solve it, i tried to give the last date now.year -3 but it doesn't work! it keeps tell me that 'The instance member 'noww' can't be accessed in an initializer.'
var noww = DateTime.now();
DateTime selectedDate = DateTime(noww.year - 3);
showDatePicker(
context: context,
initialDate: selectedDate, // Refer step 1
firstDate: DateTime(now.year - 10),
lastDate: DateTime(now.year + 1),
Declare the variable now like this
var noww;
But then after that, run the rest of the code in initState(), like this
#override
void initState(){
super.initState();
noww = DateTime.now();
DateTime selectedDate = DateTime(noww.year - 3);
showDatePicker(
context: context,
initialDate: selectedDate, // Refer step 1
firstDate: DateTime(now.year - 10),
lastDate: DateTime(now.year + 1),
);
}
#override
Widget build(context){
...
}
This is because you cannot use initialisers outside of functions.
I created a showTimePicker and I changed the format in 24h, but when I am extracting the value in the ".then" future I get the time in 12h format. Can somebody tell me where is the issue? This is the code:
void _presentTimePicker() {
showTimePicker(
context: context,
initialTime: TimeOfDay(
hour: TimeOfDay.now().hour,
minute: (TimeOfDay.now().minute - TimeOfDay.now().minute % 10 + 10)
.toInt()),
builder: (BuildContext context, Widget child) {
return MediaQuery(
data:
MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true),
child: child);
}).then((value) {
if (value == null) return;
setState(() {
time.text = TimeOfDay(
hour: value.hour,
minute: value.minute,
).format(context);
print(time.text);
});
});
}
the output is: 5:50 PM when I selected in picker 17:50
This issue is how you are changing the time of day back to a string. Try using this instead, so that you can override the default.
localizations.formatTimeOfDay(TimeOfDay(
hour: value.hour,
minute: value.minute,
), alwaysUse24HourFormat: true);
(The default is derived from MediaQuery - see here for more details of how.)
I'm trying to make my datepicker reusable, as I need three datepickers, that change different values that are stored in the same class, lets call it _object.date1 , date 2, date 3
To reuse my datepicker I tried the following and passed the variable to the datepicker that shall be changed. But then the field value isn't changed or stored and nothing happens, also no error. If I don't pass the value to _showAndroidDatePicker() and use the line in setState that I commented out below, it works properly. The Datepicker ist linked to the onTap of a TextFormField in a Form.
Can anyone explain to me what I'm missing here? It would be really great to make this reusable.
Many thanks!
void _showAndroidDatePicker(value) {
showDatePicker(
context: context,
builder: (BuildContext context, Widget child) {
return Theme(
data: ThemeData.light().copyWith(
primaryColor: Theme.of(context).primaryColor,
accentColor: Theme.of(context).primaryColor,
colorScheme:
ColorScheme.light(primary: Theme.of(context).primaryColor),
buttonTheme: ButtonThemeData(textTheme: ButtonTextTheme.primary),
),
child: child,
);
},
initialDate: DateTime.now(),
locale: Locale('de'),
firstDate: DateTime(1900),
helpText: 'Bitte wähle ein Datum aus',
lastDate: DateTime.now(),
).then<DateTime>(
(DateTime newDate) {
if (newDate != null) {
setState(() {
value = newDate.toIso8601String();
//Below code works if value isn't passed to datepicker, but I want it variable to avoid boilerplate
// _object.date1 =newDate.toIso8601String();
});
}
return;
},
);
}
Many thanks for your help!
You could pass it the controller and the focus node for the text field. Something like this:
datePickerListener(node, controller) {
if (node.hasFocus) {
node.unfocus();
showDatePicker(your setup).then((date){
var formatter = DateFormat('dd/MM/yyyy');
var formatted = formatter.format(date).toString();
controller.text = formatted;
});
}
}
Then:
FocusNode yourNode = FocusNode();
#override
void initState(){
yourNode.addListener(){
datePickerListener(yourNode, yourController);
};
}
TextFormField(
focusNode: yourNode,
controller: yourController,
)
Something like that. Just adjust to your needs.
I'm trying to print all selected dates in date range picker, is there anyway to do it?
here is my code
import 'package:flutter/material.dart';
import 'package:date_range_picker/date_range_picker.dart' as DateRagePicker;
class TryCalendar extends StatefulWidget {
#override
_TryCalendarState createState() => _TryCalendarState();
}
class _TryCalendarState extends State<TryCalendar> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
),
body: new MaterialButton(
color: Color(0xFFED7D31),
onPressed: () async {
final List<DateTime> picked = await DateRagePicker.showDatePicker(
context: context,
initialFirstDate: new DateTime.now(),
initialLastDate: (new DateTime.now()).add(new Duration(days: 7)),
firstDate: new DateTime(2015),
lastDate: new DateTime(2020)
);
if (picked != null && picked.length == 2) {
print(picked);
}
},
child: new Text("Pick date range")
)
);
}
}
I need to print all selected dates instead of first and last selected dates. Thank you!
List<DateTime> getDaysInBeteween(DateTime startDate, DateTime endDate) {
List<DateTime> days = [];
for (int i = 0; i <= endDate.difference(startDate).inDays; i++) {
days.add(startDate.add(Duration(days: i)));
}
return days;
}
picked is list of DateTime , so you should iterate every date in list then print
if (picked != null && picked.length >= 2) {
picked.forEach((date) {
print(date.toString());
});
}