Get the value of selected time and day using a DatePicker - flutter

I am trying to get the value of the selected time and date when the Datepicker is shown.
I achieved the UI and shown the date and time picker when onTap.
The problem is that I can get the value after selected. The idea would be to render it somewhere in the screen as follows:
time selected: .....
date selected: .....
This is my code regarding the popUp of the DayPicker and the function that gets the value:
function and variables:
DateTime? _dateTime;
TimeOfDay _time = TimeOfDay(hour: 7, minute: 15);
void _selectTime() async {
final newTime = await showTimePicker(
context: context,
initialTime: _time,
initialEntryMode: TimePickerEntryMode.input,
);
if (newTime != null) {
setState(() {
_time = newTime;
});
}
}
Gesture Detector to show the PickerDate:
GestureDetector(
onTap: () {
showDatePicker(
context: context,
initialDate: _dateTime ?? DateTime.now(),
firstDate: DateTime(2021),
lastDate: DateTime(2023),
builder: (BuildContext context, Widget? child) {
return Theme(
data: ThemeData.light().copyWith(
primaryColor: context.themeSettings.lightRed,
accentColor: context.themeSettings.lightRed,
colorScheme: ColorScheme.light(primary: context.themeSettings.lightRed),
buttonTheme: ButtonThemeData(textTheme: ButtonTextTheme.primary),
),
child: child!,
);
},
).then(
(date) {
setState(
() {
_dateTime = date;
},
);
print('date');
},
);
},
Gesture detector to show the DatePicker:
GestureDetector(
onTap: _selectTime,
child: Container(
decoration: BoxDecoration(
border: Border.all(color: context.themeSettings.mediumGray),
borderRadius: BorderRadius.all(Radius.circular(
5.0,
) //
),
),
width: width * 0.40,
height: height * 0.05,
child: Center(
child: Text(
'Pick a time',
style: TextStyle(fontSize: 18, color: context.themeSettings.darkText, fontWeight: FontWeight.bold),
),
),
),
),
The only thing missing is to show the actual value selected for both information.
what am I missing?

It remains only to display the time for the user. With Text().
Your time value in the _time variable
and dates in _dateTime
Text("time selected: $_time date selected: _dateTime",),
put this somewhere in your interface
for example in a child in GestureDetector
upd (24.08.2021):
I can not understand what your problem may be, according to the code fragments that you showed
Try to use code close to this
Source of code
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(primarySwatch: Colors.blue, brightness: Brightness.dark),
home: DatePickerDemo(),
);
}
}
class DatePickerDemo extends StatefulWidget {
#override
_DatePickerDemoState createState() => _DatePickerDemoState();
}
class _DatePickerDemoState extends State<DatePickerDemo> {
/// Which holds the selected date
/// Defaults to today's date.
DateTime selectedDate = DateTime.now();
_selectDate(BuildContext context) async {
final DateTime picked = await showDatePicker(
context: context,
initialDate: selectedDate,
firstDate: DateTime(2000),
lastDate: DateTime(2025),
);
if (picked != null && picked != selectedDate)
setState(() {
selectedDate = picked;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(
"${selectedDate.toLocal()}".split(' ')[0],
style: TextStyle(fontSize: 55, fontWeight: FontWeight.bold),
),
SizedBox(
height: 20.0,
),
ElevatedButton(
onPressed: () => _selectDate(context),
child: Text(
'Select date',
style:
TextStyle(color: Colors.black, fontWeight: FontWeight.bold),
),
),
],
),
),
);
}
}

Related

How can i show a 24 hour format after a showTimePicker selection in flutter?

I have created a showTimePicker dialogue and I can clearly select a specific hour in 24 hour format but i cannot display it in a text field in 24 Hour format. It falls back to a 12 Hrs format.
Here is the code i used.
GestureDetector(
onTap: () async {
final TimeOfDay? newTime = await showTimePicker(
context: context,
initialTime: trainingStartTime,
builder: (BuildContext context, Widget? child) {
return MediaQuery(
data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true),
child: child!,
);
},
);
if (newTime != null) {
setState(() {
trainingStartTime = newTime;
});
}
},
child: Container(
width: size.width * 0.12,
height: size.height * 0.05,
decoration: BoxDecoration(
border: Border.all(color: Colors.grey.shade400),
borderRadius: BorderRadius.circular(5)
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Text(
'${trainingStartTime.format(context)}',
style: const TextStyle(
//color: Colors.grey,
fontSize: 18,
),
),
Icon(Icons.access_time),
],
),
),
),
Format your selected time like this,
if (newTime != null) {
final localizations = MaterialLocalizations.of(context);
String formattedTime = localizations.formatTimeOfDay(newTime, alwaysUse24HourFormat: true);
setState(() {
initialTime = newTime;
trainingStartTime = formattedTime;
});
}
initialTime variable is used to display the selected time inside the timePicker widget and trainingStartTime displays the time inside the Text widget.
Here is the full code,
import 'package:flutter/material.dart';
class TimeExample extends StatefulWidget {
static var tag = "/TimeExample";
const TimeExample({Key? key}) : super(key: key);
#override
_TimeExampleState createState() => _TimeExampleState();
}
class _TimeExampleState extends State<TimeExample> {
String? trainingStartTime;
TimeOfDay initialTime = TimeOfDay.now();
late Size size;
#override
Widget build(BuildContext context) {
size = MediaQuery.of(context).size;
return Scaffold(
body: Center(
child: GestureDetector(
onTap: () async {
final TimeOfDay? newTime = await showTimePicker(
context: context,
initialTime: initialTime,
builder: (BuildContext context, Widget? child) {
return MediaQuery(
data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true),
child: child!,
);
},
);
if (newTime != null) {
final localizations = MaterialLocalizations.of(context);
String formattedTime = localizations.formatTimeOfDay(newTime, alwaysUse24HourFormat: true);
setState(() {
initialTime = newTime;
trainingStartTime = formattedTime;
});
}
},
child: Container(
width: size.width * 0.9,
height: size.height * 0.05,
decoration: BoxDecoration(border: Border.all(color: Colors.grey.shade400), borderRadius: BorderRadius.circular(5)),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [Expanded(child: Text(trainingStartTime ?? 'N/A', style: const TextStyle(fontSize: 18))), Icon(Icons.access_time)],
),
),
),
),
);
}
}

How to use timepicker widget to show start and end time using Flutter

I am creating a page to show start time and end time but when I couldn't find a way to update the time in individual fields. I am only using a single function to build a timepicker and showing the time.
Here is my timepicker function
Future<Null> selectedTime(BuildContext context, bool ifPickedTime) async{
_pickedTime = await showTimePicker(
context: context,
initialTime: _currentTime);
if (_pickedTime != null){
setState(() {
_currentTime = _pickedTime;
print("The picked time is: $_pickedTime");
});
}
}
This is my Widget Builder
Widget _buildTimePick(String title, bool ifPickedTime){
return Row(
children: [
Container(
width: 80,
child: Text(
title,
style: AppStyles.textTitle,
),
),
Container(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 5),
decoration: BoxDecoration(
border: Border.all(color: MyColors.borderColor),
borderRadius: BorderRadius.circular(20),
),
child: GestureDetector(
child: Text(
"${_currentTime.format(context)}",
style: AppStyles.textBody,
),
onTap: () {
selectedTime(context, ifPickedTime);
},
),
),
],
);
}
According to the question, I feel that what you want to achieve is that you want to update the start and the end time individually. But according to the code only one time is updated which is shared by both start the end time widget, so it shows the same time.
What you can do is create 2 variables one for start time and one for end time.
TimeOfDay _startTime;
TimeOfDay _endTime;
Then make your _buildTimePick function a little more flexible by passing the time to display.
Widget _buildTimePick(String title, bool ifPickedTime, TimeOfDay currentTime, Function(TimeOfDay) onTimePicked){
return Row(
children: [
Container(
width: 80,
child: Text(
title,
style: AppStyles.textTitle,
),
),
Container(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 5),
decoration: BoxDecoration(
border: Border.all(color: MyColors.borderColor),
borderRadius: BorderRadius.circular(20),
),
child: GestureDetector(
child: Text(
currentTime.format(context),
style: AppStyles.textBody,
),
onTap: () {
selectedTime(context, ifPickedTime,currentTime, onTimePicked);
},
),
),
],
);
}
Also the selectedTime function should be more flexible such that it can be used
for selecting both start and end time by creating a callback.
Future selectedTime(BuildContext context, bool ifPickedTime, TimeOfDay initialTime, Function(TimeOfDay) onTimePicked) async{
var _pickedTime = await showTimePicker(
context: context,
initialTime: initialTime);
if (_pickedTime != null){
onTimePicked(_pickedTime);
}
}
So, the final code might look something like :
import 'package:flutter/material.dart';
void main() => runApp(MainApp());
class MainApp extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return MyAppState();
}
}
class MyAppState extends State<MainApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(),
body: Home(),
));
}
}
class Home extends StatefulWidget {
#override
State<Home> createState() => HomeState();
}
class HomeState extends State<Home> {
TimeOfDay startTime = TimeOfDay.now();
TimeOfDay endTime = TimeOfDay.now();
#override
Widget build(BuildContext context) {
return ListView(
children: [
_buildTimePick("Start", true, startTime, (x) {
setState(() {
startTime = x;
print("The picked time is: $x");
});
}),
const SizedBox(height: 10),
_buildTimePick("End", true, endTime, (x) {
setState(() {
endTime = x;
print("The picked time is: $x");
});
}),
],
);
}
Future selectedTime(BuildContext context, bool ifPickedTime,
TimeOfDay initialTime, Function(TimeOfDay) onTimePicked) async {
var _pickedTime =
await showTimePicker(context: context, initialTime: initialTime);
if (_pickedTime != null) {
onTimePicked(_pickedTime);
}
}
Widget _buildTimePick(String title, bool ifPickedTime, TimeOfDay currentTime,
Function(TimeOfDay) onTimePicked) {
return Row(
children: [
SizedBox(
width: 80,
child: Text(
title,
),
),
Container(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 5),
decoration: BoxDecoration(
border: Border.all(),
borderRadius: BorderRadius.circular(20),
),
child: GestureDetector(
child: Text(
currentTime.format(context),
),
onTap: () {
selectedTime(context, ifPickedTime, currentTime, onTimePicked);
},
),
),
],
);
}
}
You can update the TextField using TextEditingController. Put in in the setState so it can update the TextField whenever you pick a date.
Exp:
final txtController = TextEditingController();
final DateTime? picked = await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2000),
lastDate: DateTime(2025));
if(picked != null && picked != now) {
setState(() {
txtController.text = DateFormat('dd-MM-yyyy').format(picked); //I'm using intl package, you can use toString()
});
}

Flutter:1 positional argument(s) expected, but 0 found

I am working on a flutter project, which separated the body: widget from the main.dart and placed it inside a new statefull widget with the file name todu_list.dart now i am trying to call it back to main.dart file body: SingleChildScrollView(child: Lists()), and am getting this error
1 positional argument(s) expected, but 0 found.
Try adding the missing arguments.
I have gone through alot of similar questions here on StackOverFlow and realised i am supposed to add an argument inside the brackets "()" but i don't know which of the function from my Lists widget that i am expected to call there
Below is the "Lists" widget code
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import '../models/todus.dart';
import 'package:intl/intl.dart';
import 'package:sqflite/sqflite.dart';
import '../models/database_helper.dart';
class Lists extends StatefulWidget {
final Function addTx;
Lists(this.addTx);
#override
_ListsState createState() => _ListsState();
}
class _ListsState extends State<Lists> {
final dbHelper = DatabaseHelper.instance;
void _addNewTransaction(BuildContextcontext) {
showModalBottomSheet(
backgroundColor: Colors.white,
isScrollControlled: true,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(25.0))),
context: context,
builder: (_) {
return GestureDetector(
onTap: () {},
// Where i started the code pasting from
child: Padding(
padding: MediaQuery.of(context).viewInsets,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Card(
elevation: 0.000,
child: Container(
padding: EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
TextField(
decoration: InputDecoration(labelText: 'Title'),
controller: _titleController,
autofocus: true,
onSubmitted: null,
// onChanged: (val) {
// titleInput = val;
// },
),
TextField(
decoration: InputDecoration(labelText: 'Description'),
controller: _discriptionController,
onSubmitted: null,
// onChanged: (val) => amountInput = val,
),
Container(
height: 70,
child: Row(
children: [
Text(selectedDateAndTime == null
? 'No Date Choosen'
: DateFormat('MM/dd/yyyy HH:mm')
.format(selectedDateAndTime)
// : DateFormat.yMd()
// .format(_selectedDate),
),
FlatButton(
textColor: Theme.of(context).primaryColor,
child: Icon(Icons.calendar_today),
// onPressed: () async {
// var value = await _selectedTime();
// },
onPressed: () => _selectDayAndTimeL(context),
),
],
),
),
RaisedButton(
child: Text('Save Todo'),
color: Theme.of(context).primaryColor,
textColor: Theme.of(context).textTheme.button.color,
onPressed: _submitData,
),
],
),
),
),
),
),
);
},
);
}
final _titleController = TextEditingController();
final _discriptionController = TextEditingController();
var favorite;
// DateTime _selectedDate;
DateTime selectedDateAndTime;
#override
void dispose() {
super.dispose();
_discriptionController.dispose();
_titleController.dispose();
}
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('...');
}
List<ItemLists> items = [
ItemLists(
title: 'Best Music of the Year',
description: 'Davido',
favorite: false,
),
ItemLists(
title: 'Best Album Cover design',
description: 'Brighter Press',
favorite: false,
),
void _submitData() {
// if (_amountController.text.isEmpty) {
// return;
// }
final enteredTitle = _titleController.text;
final enteredDescription = _discriptionController.text;
if (enteredTitle.isEmpty) {
return;
}
widget.addTx(
enteredTitle,
enteredDescription,
selectedDateAndTime,
);
Navigator.of(context).pop();
}
#override
Widget build(BuildContext context) {
return SizedBox(
child: Container(
child: ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemBuilder: (context, index) {
return Dismissible(
key: ObjectKey(items[index]),
background: Container(
color: Colors.red,
),
child: Card(
child: ListTile(
leading: new IconButton(
icon: Icon(
Icons.check,
color:
items[index].favorite ? Colors.green : Colors.grey,
),
tooltip: 'Add to Favorite',
onPressed: () {
setState(() {
items[index].favorite = !items[index].favorite;
});
}),
title: Text('${items[index].title}'),
subtitle: Text('${items[index].description}'),
trailing: IconButton(
icon: Icon(Icons.calendar_today),
onPressed: () => _selectDayAndTimeL(context),
),
)),
onDismissed: (direction) {
final String myTitle = items[index].title;
// Remove the item from the data source.
setState(() {
var deletedItems = items.removeAt(index);
Scaffold.of(context).showSnackBar(
SnackBar(
content: Text('$myTitle Deleted'),
action: SnackBarAction(
label: 'Undo',
onPressed: () => setState(
() => items.insert(index, deletedItems),
)),
),
);
});
});
},
itemCount: items.length,
),
),
);
floatingActionButton:
FloatingActionButton(
child: Icon(Icons.add),
onPressed: () => _addNewTransaction(context),
backgroundColor: Colors.redAccent,
);
}
}
You have to give a function as parameter in order to build your widget. This is not a function of your widget that you will be calling but the function addTx that you will be calling from within your Lists widget.
Either remove the parameter or pass a function to solve it.
Example: since your function is expected to have 3 parameters:
widget.addTx(
enteredTitle,
enteredDescription,
selectedDateAndTime,
);
you can create:
void addTitleDescDate(string title, string description, string date) { // NB you should probably use a Date object or epoch time.
print(title);
print(description);
print(date);
}
And you use this function Lists(addTitleDescDate)
As a side note I don't really see the point to have this function as a parameter shared to the Lists widget, but if you want to learn more about function as parameter that is still interesting.

Convert DateTime into millisecondsSinceEpoch using DateTimeField in flutter

I need to convert the user inputted time to milli seconds Since Epoch (millisecondsSinceEpoch). I was looking for a solution for this but I could found only millisecondsSinceEpoch to regular time. So here is my code. I tried to do this in this way. Anyone can help, I really appreciate it.
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:intl/intl.dart';
import 'package:datetime_picker_formfield/datetime_picker_formfield.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
// This widget is the root of your application.
_timeDateConvertToMili createState() => _timeDateConvertToMili();
}
class _timeDateConvertToMili extends State<MyApp>{
final format = DateFormat("dd-MM-yyyy HH:mm");
final initialValue = DateTime.now();
bool autoValidate = false;
bool showResetIcon = true;
DateTime value = DateTime.now();
TextEditingController _startTimeController = TextEditingController();
TextEditingController _endTimeController = TextEditingController();
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Container(
child: Column(
children: [
SizedBox(height: 50,),
Container(
padding: EdgeInsets.all(5.0),
decoration: BoxDecoration(
border: Border(
// bottom: BorderSide(color: Colors.grey[100])
)),
child: DateTimeField(
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Start Time',
labelStyle: TextStyle(color: Colors.black),
),
style: TextStyle(
color: Colors.black,
),
controller: _startTimeController,
format: format,
onShowPicker: (context, currentValue) async {
final date = await showDatePicker(
context: context,
firstDate: DateTime(2000),
initialDate: currentValue ?? DateTime.now(),
lastDate: DateTime(2100));
if (date != null) {
final time = await showTimePicker(
context: context,
initialTime:
TimeOfDay.fromDateTime(currentValue ?? DateTime.now()),
);
return DateTimeField.combine(date, time);
} else {
return currentValue;
}
},
resetIcon: showResetIcon ? Icon(Icons.delete) : null,
),
),
Container(
padding: EdgeInsets.all(5.0),
decoration: BoxDecoration(
border: Border(
// bottom: BorderSide(color: Colors.grey[100])
)),
child: DateTimeField(
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'End Time',
labelStyle: TextStyle(color: Colors.black),
),
style: TextStyle(
color: Colors.black,
),
controller: _endTimeController,
format: format,
onShowPicker: (context, currentValue) async {
final date = await showDatePicker(
context: context,
firstDate: DateTime(2000),
initialDate: currentValue ?? DateTime.now(),
lastDate: DateTime(2100));
if (date != null) {
final time = await showTimePicker(
context: context,
initialTime:
TimeOfDay.fromDateTime(currentValue ?? DateTime.now()),
);
return DateTimeField.combine(date, time);
} else {
return currentValue;
}
},
resetIcon: showResetIcon ? Icon(Icons.delete) : null,
),
),
Container(
child: RaisedButton(
onPressed: () {
convertNow();
},
child: Text('Convert to Epoch'),
),
),
Container(
child: Text('Result is :'
),
),
],
),
),
),
);
}
void convertNow() {
print ('inputted time is : $_startTimeController');
//var unix = DateTime.parse(_startTimeController.toString()).millisecondsSinceEpoch / 1000;
}
}
Thanks in advance
Here I got the result.
Change the time date format final format = DateFormat("yyyy-MM-dd HH:mm");
void convertNow() {
var inputedStartTime = DateTime.parse(startTimeController.text);
var mili = inputedStartTime.millisecondsSinceEpoch/1000;
var startTime = mili.toInt();
var inputedEndtTime = DateTime.parse(endTimeController.text);
var mili2 = inputedEndtTime.millisecondsSinceEpoch/1000;
var endTime = mili2.toInt();
<!--Result see on run / terminal-->
print ('Converted start time is $startTime');
print ('Converted end time is $endTime');
}

How do I change a CheckboxListTile's title after a specific event?

I've gotten stuck trying to get this to work, basically I have a ListView with two CheckBoxListTiles inside it, when a user selects a CheckBoxListTile a modal pops up with a DatePicker, what I want to achieve is after the user selects the date, the CheckBoxListTile text (or title I guess) gets changed to the date, here is my code so far.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart' show timeDilation;
class ChecklistWidget extends StatefulWidget {
#override
_ChecklistWidget createState() => _ChecklistWidget();
}
class _ChecklistWidget extends State<ChecklistWidget> {
String date1 = "";
String date2 = "";
Map<String, bool> values = {
'Choose a specific date': false,
'Choose an alternative date': false,
};
#override
Widget build(BuildContext build){
return new ListView(
shrinkWrap: true,
children: values.keys.map((String key) {
return new CheckboxListTile(
title: new Text(key),
value: values[key],
onChanged: (bool value) {
setState(() {
values[key] = value;
showCupertinoModalPopup(context: context, builder: (BuildContext context) { return _buildDatePicker(
CupertinoDatePicker(
mode: CupertinoDatePickerMode.dateAndTime,
initialDateTime: DateTime.now(),
onDateTimeChanged: (DateTime newDateTime) {
// date1 = newDateTime.toString();
print("Your Selected Date: ${newDateTime.day}");
},
),
); });
});
title: date1;
},
);
}).toList(),
);
}
Widget _buildDatePicker(Widget picker){
return Container(
height: 216.0,
padding: const EdgeInsets.only(top: 6.0),
color: CupertinoColors.white,
child: DefaultTextStyle( style: const TextStyle(
color: CupertinoColors.black,
fontSize: 22.0,
),
child: GestureDetector(
// Blocks taps from propagating to the modal sheet and popping.
onTap: () {},
child: SafeArea(
top: false,
child: picker,
),
),)
);
}
}
Any help is appreciated, I'm new to flutter so I'm sure I'm just missing something, but I cant wrap my head around it.
I suggest you don't loop over the map keys because you have a limited amount of dates so it's better to just build each date and update its value accordingly.
If you did actually have an unknown number of dates it's better to store each one in a model with a label, value and enabled fields.
But this is enough for your case:
class _ChecklistWidget extends State<ChecklistWidget> {
String date1;
String date2;
bool specificDateEnabled = false;
bool alternativeDateEnabled = false;
#override
Widget build(BuildContext build) {
return new ListView(shrinkWrap: true, children: [
CheckboxListTile(
title: Text(date1 ?? 'Choose a specific date'),
value: specificDateEnabled,
onChanged: (bool value) {
setState(() {
specificDateEnabled = value;
showCupertinoModalPopup(
context: context,
builder: (BuildContext context) {
return _buildDatePicker(
CupertinoDatePicker(
mode: CupertinoDatePickerMode.dateAndTime,
initialDateTime: DateTime.now(),
onDateTimeChanged: (DateTime newDateTime) {
setState(() {
date1 = newDateTime.toString();
});
},
),
);
});
});
},
),
CheckboxListTile(
title: Text(date2 ?? 'Choose an alternative date'),
value: alternativeDateEnabled,
onChanged: (bool value) {
setState(() {
alternativeDateEnabled = value;
showCupertinoModalPopup(
context: context,
builder: (BuildContext context) {
return _buildDatePicker(
CupertinoDatePicker(
mode: CupertinoDatePickerMode.dateAndTime,
initialDateTime: DateTime.now(),
onDateTimeChanged: (DateTime newDateTime) {
setState(() {
date2 = newDateTime.toString();
});
},
),
);
});
});
},
),
]);
}
Widget _buildDatePicker(Widget picker){
return Container(
height: 216.0,
padding: const EdgeInsets.only(top: 6.0),
color: CupertinoColors.white,
child: DefaultTextStyle( style: const TextStyle(
color: CupertinoColors.black,
fontSize: 22.0,
),
child: GestureDetector(
// Blocks taps from propagating to the modal sheet and popping.
onTap: () {},
child: SafeArea(
top: false,
child: picker,
),
),)
);
}
}