import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:shared_preferences/shared_preferences.dart';
class MyDateTimePicker extends StatefulWidget {
final Function(DateTime) onDateSelected;
MyDateTimePicker({required this.onDateSelected});
@override
_MyDateTimePickerState createState() => _MyDateTimePickerState();
}
class _MyDateTimePickerState extends State<MyDateTimePicker> {
DateTime selectedDate = DateTime.now();
bool showYearPicker = false;
bool showMonthPicker = false;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => _showDatePicker(context),
child: Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(8.0),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
_buildPickerItem(
DateFormat('y').format(selectedDate),
),
_buildPickerItem(
DateFormat('MMMM').format(selectedDate),
),
_buildPickerItem(
DateFormat('dd').format(selectedDate),
),
],
),
),
);
}
Widget _buildPickerItem(String text) {
return Container(
padding: EdgeInsets.all(8.0),
child: Text(
text,
style: TextStyle(fontSize: 18.0),
),
);
}
Future<void> _showDatePicker(BuildContext context) async {
print("showdate");
final DateTime? pickedDate = await showDatePicker(
context: context,
initialDate: selectedDate,
firstDate: DateTime(selectedDate.year - 1),
lastDate: DateTime(selectedDate.year + 1),
);
if (pickedDate != null && pickedDate != selectedDate) {
setState(() {
selectedDate = pickedDate;
});
saveSelectedDate(selectedDate);
// Call the callback to notify the parent widget of the selected date
widget.onDateSelected(selectedDate);
}
}
}
void saveSelectedDate(DateTime date) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setString('selectedDate', date.toIso8601String());
}
Comments
Post a Comment