how to get flutter textfield value to datepicker - flutter

When I enter date in text field in "MM/dd/yyyy" than how to assign same value to date picker
Stack(
alignment: Alignment.centerRight,
children: [
TextFormField(
controller: birthDateInputController,
validator: Utils.birthDateValidator,
inputFormatters: [
FilteringTextInputFormatter.singleLineFormatter,
birthDateInput,
],
),
IconButton(
icon: Icon(
Icons.calendar_today_rounded,
),
onPressed: () async {
FocusScope.of(context).requestFocus(FocusNode());
DateTime pickedDate = await showDate();
if (pickedDate != null) {
setState(() {
intl.DateFormat formatter =
intl.DateFormat('MM/dd/yyyy');
String formatted = formatter.format(pickedDate);
birthDateInputController.text = formatted;
birthDate = pickedDate;
});
}
},
),
],
),
Future<DateTime> showDate() async {
return await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(1920),
lastDate: DateTime.now(),
);
}
and When I select value to date picker than assign to the text field
but when I enter date in text field than can't assign to the date picker

For Assign to DatePicker. you need to add couple of things in Future<DateTime> showDate(String dateTime)
Future<DateTime> showDate(String dateTime) async {
DateTime _dateTime;
if (dateTime.isNotEmpty) {
_dateTime = DateFormat('MM/dd/yyyy').parse(dateTime);
} else {
_dateTime = DateTime.now();
}
return await showDatePicker(
context: context,
initialDate: _dateTime,
firstDate: DateTime(1920),
lastDate: DateTime.now(),
);
}
Pass your text in this showDate() Method in onPressed
onPressed: () async {
FocusScope.of(context).requestFocus(FocusNode());
DateTime pickedDate = await showDate(birthDateInputController.text);
if (pickedDate != null) {
setState(() {
intl.DateFormat formatter =
intl.DateFormat('MM/dd/yyyy');
String formatted = formatter.format(pickedDate);
birthDateInputController.text = formatted;
birthDate = pickedDate;
});
}
},
And in TextFormField you only have to pass the number and forward slash for that
TextFormField(
controller: birthDateInputController,
validator: Utils.birthDateValidator,
keyboardType: TextInputType.datetime, // use this parameter
inputFormatters: [
FilteringTextInputFormatter.singleLineFormatter,
FilteringTextInputFormatter.allow(RegExp('[0-9/]')), // for numbers only
LengthLimitingTextInputFormatter(10), //set the number limit including slash
birthDateInput,
],
),
Make a validation which the date is correct format when typing

In your showDate() function you used initialDate: DateTime.now() which take the todays date as initial date
So now you should set the initialDate as manually
Try to implement showDate() method like
Future<DateTime> showDate(int year, int month, int day, int hr, int min, int sec) async {
return await showDatePicker(
context: context,
initialDate: DateTime(year, month, day, hr, min, sec),
firstDate: DateTime(1920),
lastDate: DateTime.now(),
);
}

Related

I want add CupertinoDatePicker and minimum day should be date before 2 years from today and maximum date should be date before 1 year from today

I tried to add minimum day should be date before 2 years from today and maximum date should be date before 1 year from today. But show this error
code
DateTime min = new DateTime.now();
DateTime max = new DateTime.now();
DateTime mindate = new DateTime(min.year, min.month - 2, 0);
DateTime maxdate = new DateTime(max.year, max.month - 1, 0);
DateTime? selectedDate;
void showDatePicker() {
showCupertinoModalPopup(
context: context,
builder: (BuildContext builder) {
return Container(
height: MediaQuery.of(context).copyWith().size.height * 0.25,
color: Colors.white,
child: CupertinoDatePicker(
mode: CupertinoDatePickerMode.date,
initialDateTime: mindate,
onDateTimeChanged: (value) {
if (value != null && value != selectedDate)
setState(() {
selectedDate = value;
});
},
maximumDate: maxdate,
minimumDate: mindate,
),
);
});
}
Try this:
DateTime? selectedDate;
DateTime now = new DateTime.now();
void showDatePicker() {
DateTime mindate = new DateTime(now.year - 2, now.month, now.day);
DateTime maxdate = new DateTime(now.year - 1, now.month, now.day);
showCupertinoModalPopup(
context: context,
builder: (BuildContext builder) {
return Container(
height: MediaQuery.of(context).copyWith().size.height * 0.25,
color: Colors.white,
child: CupertinoDatePicker(
mode: CupertinoDatePickerMode.date,
initialDateTime: mindate,
onDateTimeChanged: (value) {
if (value != null && value != selectedDate)
setState(() {
selectedDate = value;
});
},
maximumDate: maxdate,
minimumDate: mindate,
),
);
});
}

Flutter Date Picker function for multiple fields

How to use the below code for single function multiple textformfield controller to pass the date value. Or I have to write multiple function for all controllers in the form fields for date picker ?
....
TextFormField(
decoration: inputDecoration(
'Enter Start Date',
'Start Date',
datestartCtrl),
controller: datestartCtrl,
onTap: () => _selectDate(context),
),
SizedBox(
height: 10,
),
TextFormField(
decoration: inputDecoration(
'Enter Finish Date',
'Date Finished',
datefinishCtrl),
controller: datefinishCtrl,
onTap: () => _selectDate(context),
),
.....
Future<Null> _selectDate(BuildContext context) async {
var selectedDate = DateTime.now();
DateFormat formatter = DateFormat('dd MMMM yyyy');//specifies day/month/year format
final DateTime? picked = await showDatePicker(
context: context,
initialDate: selectedDate,
firstDate: DateTime(1901, 1),
lastDate: DateTime.now());
if (picked != null && picked != selectedDate)
setState(() {
selectedDate = picked;
datestartCtrl.value = TextEditingValue(text: formatter.format(picked));//Use formatter to format selected date and assign to text field
});
}
TextFormField(
decoration: inputDecoration(
'Enter Start Date',
'Start Date',
datestartCtrl),
controller: datestartCtrl,
onTap: () => _selectDate(context,datestartCtrl),
),
SizedBox(
height: 10,
),
TextFormField(
decoration: inputDecoration(
'Enter Finish Date',
'Date Finished',
datefinishCtrl),
controller: datefinishCtrl,
onTap: () => _selectDate(context,datefinishCtrl),
),
Method for datepicker
Future<Null> _selectDate(BuildContext context, TextEditingController controller) async {
var selectedDate = DateTime.now();
DateFormat formatter = DateFormat('dd MMMM yyyy');
final DateTime? picked = await showDatePicker(
context: context,
initialDate: selectedDate,
firstDate: DateTime(1901, 1),
lastDate: DateTime.now());
if (picked != null && picked != selectedDate)
setState(() {
controller.value = TextEditingValue(text: formatter.format(picked));
});
}
Textfield code :
TextFormField(
decoration: inputDecoration(
'Enter Start Date',
'Start Date',
datestartCtrl),
controller: datestartCtrl,
onTap: () => _selectDate(context,datestartCtrl),
),
SizedBox(
height: 10,
),
TextFormField(
decoration: inputDecoration(
'Enter Finish Date',
'Date Finished',
datefinishCtrl),
controller: datefinishCtrl,
onTap: () => _selectDate(context,datefinishCtrl),
),
Method For Datepicker
Future<Null> _selectDate(BuildContext context, TextEditingController controller) async {
var selectedDate = DateTime.now();
DateFormat formatter = DateFormat('dd MMMM yyyy');
final DateTime? picked = await showDatePicker(
context: context,
initialDate: selectedDate,
firstDate: DateTime(1901, 1),
lastDate: DateTime.now());
if (picked != null && picked != selectedDate)
setState(() {
selectedDate = picked;
controller.text = picked.tostring();
});
}
Hope you got the solution!

display selected date in a form field for flutter

I am trying to work out how I can display the selected date back into a formfield for Flutter. If I just use a Text element it works fine
TextFormField(
onTap: _selectDate,
enabled: true,
initialValue: DateFormat("E, d MMM yyyy")
.format(_date)
.toString(),
readOnly: true,
decoration: InputDecoration(labelText: 'Date'),
),
SizedBox(height: 8),
Text(DateFormat("E, d MMM yyyy")
.format(_date)
.toString()),
void _selectDate() async {
final DateTime newDate = await showDatePicker(
context: context,
initialDate: _date,
firstDate: DateTime.now(),
lastDate: DateTime.now().add(Duration(days: 90)),
helpText: 'Select date for task',
);
if (newDate != null) {
setState(() {
_date = newDate;
});
}
}
Please try creating a TextEditingController and assign the controller to the TextFormField then set controller.text to the value you want to assign in setState. See the sample code below for reference.
TextEditingController _dateController = TextEditingController();
TextFormField(
controller: _dateController,
onTap: _selectDate,
enabled: true,
initialValue: DateFormat("E, d MMM yyyy")
.format(_date)
.toString(),
readOnly: true,
decoration: InputDecoration(labelText: 'Date'),
),
SizedBox(height: 8),
Text(DateFormat("E, d MMM yyyy")
.format(_date)
.toString()),
void _selectDate() async {
final DateTime newDate = await showDatePicker(
context: context,
initialDate: _date,
firstDate: DateTime.now(),
lastDate: DateTime.now().add(Duration(days: 90)),
helpText: 'Select date for task',
);
if (newDate != null) {
setState(() {
_date = newDate;
_dateController.text = _date.toString();
});
}
}

remove time from DatePicker

i want to remove time from DatePicker i tried this but facing this error "the getter day was called on null" i am using initial date from firbase profile.date
DateFormat and TextEditingController:
var myFormat = DateFormat('d-MM-yyyy');
TextEditingController _datecontroller = new TextEditingController();
This is from where the dialog is called:
ListTile(
title: Text('Select DOB'),
leading: Icon(Icons.calendar_today),
subtitle: TextField(
controller: _datecontroller,
decoration: InputDecoration(
hintText: ('${myFormat.format(_profile?.dob)}'),
),
),
onTap: () => _selectDate(context),
),
And the selectDate function:
Future<Null> _selectDate(BuildContext context) async {
final DateTime picked = await showDatePicker(
context: context,
initialDate: _profile?.dob ?? DateTime(2000),
firstDate: DateTime(1950),
lastDate: DateTime.now(),
);
if (picked != null && picked != _profile?.dob) {
_formKey.currentState.save();
_profile?.dob = picked;
_bloc.dispatch(UpdateEvent(_profile));
}
}

How to show date picker on the onclick of text field instead of keyboard in flutter?

Wish to show date picker when clicking on the TextFormField instead of the keyboard. I have tried using GestureDetector but not working as I expected.
DateTime _date = new DateTime.now();
TimeOfDay _time = new TimeOfDay.now();
Future<Null> _selectedDate(BuildContext context) async {
final DateTime picked = await showDatePicker(
context: context,
initialDate: _date,
firstDate: new DateTime(2016),
lastDate: new DateTime(2019));
if (picked != null && picked != _date) {
print("Date selected ${_date.toString()}");
setState(() {
_date = picked;
});
}
}
......
new GestureDetector(
onTap: (){
_selectedTime(context);
},
child:
new TextFormField(
initialValue: convertToDate(_date),
decoration: const InputDecoration(
icon: const Icon(Icons.calendar_today),
hintText: 'Enter your date of event',
labelText: 'Date',
),
keyboardType: null,
),
),
You can wrap your TextField with AbsorbPointer , so your widget tree would look something like this:
GestureDetector(
onTap:()=>showDialog(),
child:AbsorbPointer(
child: MyTextField(),
)
)
You can wrap your TextFormField with an AbsorbPointer (see documentation). It will "absorb" the incoming standard behavior on the child so clicking the TextFormField would do nothing. If you now wrap the AbsorbPointerusing a GestureDetector you can use the onTap() method to call your showDatePicker method.
DateTime selectedDate = DateTime.now();
TextEditingController _date = new TextEditingController();
Future<Null> _selectDate(BuildContext context) async {
final DateTime picked = await showDatePicker(
context: context,
initialDate: selectedDate,
firstDate: DateTime(1901, 1),
lastDate: DateTime(2100));
if (picked != null && picked != selectedDate)
setState(() {
selectedDate = picked;
_date.value = TextEditingValue(text: picked.toString());
});
}
// inside Widget build
GestureDetector(
onTap: () => _selectDate(context),
child: AbsorbPointer(
child: TextFormField(
controller: _date,
keyboardType: TextInputType.datetime,
decoration: InputDecoration(
hintText: 'Date of Birth',
prefixIcon: Icon(
Icons.dialpad,
color: _icon,
),
),
),
),
);
The other answers here have many widgets to get the job done. But this can simply done by using TextFormField only. Just set the widget to read only (so that it doesn't take inputs) and then define an onTap. The controller attached to it will take the value from the date picker.
First create a TextFormField widget like this:
TextFormField(
readOnly: true, //this is important
onTap: _selectDate, //the method for opening data picker
controller: _textcontroller, //the controller
),
Now write the _selectDate function:
DateTime dateTime = DateTime.now();
_selectDate() async {
final DateTime? picked = await showDatePicker(
context: context,
initialDate: dateTime,
initialDatePickerMode: DatePickerMode.day,
firstDate: DateTime.now(),
lastDate: DateTime(2101));
if (picked != null) {
dateTime = picked;
//assign the chosen date to the controller
_textController.text = DateFormat.yMd().format(dateTime);
}
}
Personally I think this is the easiest solution.
Try this
GestureDetector(
onTap: () => _selectDate(context),
child: AbsorbPointer(
child: TextField(
controller: textController,
decoration: InputDecoration(
focusedBorder: InputBorder.none,
enabledBorder: InputBorder.none,
contentPadding: EdgeInsets.all(10.0),
labelText: widget.hintText,
labelStyle: TextStyle(
color: Colors.black,
fontSize: 16),
// pass the hint text parameter here
hintStyle: TextStyle(
color: Colors.black,
fontSize: 16),
suffixIcon: Icon(
Icons.calendar_today),
),
style: TextStyle(color: Colors.black, fontSize: 18),
),
),
);
Future<Null> _selectDate(BuildContext context) async {
final DateTime? picked = await showDatePicker(
context: context,
initialDate: selectedDate,
firstDate: DateTime(1901, 1),
lastDate: DateTime(2100));
if (picked != null && picked != selectedDate)
setState(() {
selectedDate = picked;
String convertedDateTime = "${picked.year.toString()}-${picked.month.toString().padLeft(2,'0')}-${picked.day.toString().padLeft(2,'0')}";
// widget.textController.value = TextEditingValue(text: picked.toString());
widget.textController.value = TextEditingValue(text: convertedDateTime);;
});
}
Result
TextField(
controller: TextEditingController()
..text = reservationProvider.date,
decoration: InputDecoration(
suffixIcon: ImageIcon(
AssetImage('images/calendar_today.png'),
color: Colors.black,
)),
readOnly: true,
onTap: () async {
final date = await showDatePicker(
context: context,
firstDate: DateTime(1960),
initialDate: DateTime.now(),
lastDate: DateTime(2100));
if (date != null) {
print(date);
}
},
),