Search code examples
flutterdartdatepicker

How do I change the datepicker format flutter


enter image description here

How do I change the format of the date? I am using a datepicker to pick a date but I want the date to display as dd/mm/yyyy, here is the code

class DatePicker extends StatefulWidget {
  const DatePicker({Key? key}) : super(key: key);
  @override
  State<DatePicker> createState() => _DatePickerState();
}
class _DatePickerState extends State<DatePicker> {
  DateTime selectedDate = DateTime.now();
  Future<void> _selectDate(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
        context: context,
        initialDate: selectedDate,
        firstDate: DateTime(2015, 8),
        lastDate: DateTime(2101));
    if (picked != null && picked != selectedDate) {
      setState(() {
        selectedDate = picked;
      });
    }
  }
  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        InkWell(
            onTap: () => _selectDate(context),
            child: Text("${selectedDate.toLocal()}".split(' ')[0])),
        SizedBox(
          height: 20.0,
        ),
      ],
    );
  }
}

Solution

  • For displaying the date you should use this

    Text("${selectedDate.day}/${selectedDate.month}/${selectedDate.year}"),