Home > front end >  How to show selected date inside the button ---- Date picker -- Flutter
How to show selected date inside the button ---- Date picker -- Flutter

Time:02-14

I have built a date picker where users can select the date and I want to update the selected date inside the elevated button, but when the date is updated it also starts showing the time inside the elevated button Also, I want to keep the same format of date, I have specified above in the code I am providing my code and snapshots

[class CashInCashOut extends StatefulWidget {
  const CashInCashOut({Key? key}) : super(key: key);

  @override
  _CashInCashOutState createState() => _CashInCashOutState();
}

class _CashInCashOutState extends State<CashInCashOut> {
  DateTime date = DateTime.now();
  late var formattedDate = DateFormat('d-MMM-yy').format(date);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("Cash Out"),
        ),
        body: Padding(
          padding: const EdgeInsets.all(20.0),
          child: Column(
            children: \[
              const TextField(
                keyboardType: TextInputType.phone,
                decoration: InputDecoration(labelText: "Amount"),
              ),
              const TextField(
                decoration: InputDecoration(labelText: "Detail (optional)"),
              ),
              Row(
                children: \[
                  ElevatedButton(
                    child: Text(formattedDate),
                    onPressed: () async {
                      DateTime? _newDate = await showDatePicker(
                        context: context,
                        initialDate: date,
                        firstDate: DateTime(2022),
                        lastDate: DateTime(2030),
                      );
                      setState(() {
                        if (_newDate == null) {
                          return;
                        } else {
                          formattedDate = _newDate.toString();
                        }
                      });
                    },
                  ),
                  const Spacer(),
                  ReusableButton(text: "Add bills"),
                \],
              ),
            \],
          ),
        ));
  }
}

enter image description here

if you press the button and you chose for example this date 25-mar-2025 :

enter image description here

then click ok, the date will appear in the button :

enter image description here

CodePudding user response:

You should format the date when the button is pressed Just replace this code portion with yours

if (_newDate == null) {
      return
   } else {
      formattedDate = DateFormat.yMd().format(_newDate);

}

Note: you can change date format according to what you want just change 'yMd' to any other format you want, hover after DateFormat and your IDE will help you

  • Related