0

I want to display the text when I pick the date from showDatePicker, but now click the date is not going to update the text.

Only after I close and reopen the AlertDialog it will update but i want to update the value after I choose the date on showDatePicker and confirm it.

How can I do?

DateTime putdate = DateTime.now();

Future openDialog() => showDialog(
    context: context,
    builder: (context) => AlertDialog(
      title: const Text(
        'Choose Date',
        style: TextStyle(fontWeight: FontWeight.bold, color: Colors.red),
      ),
      content: SizedBox(
        height: 280,
        child: 
            Row(
              children: [
                IconButton(
                  icon: const Icon(Icons.calendar_month),
                  onPressed: () async {
                    DateTime? newDate = await showDatePicker(
                      context: context,
                      initialDate: putdate,
                      firstDate: DateTime(2000),
                      lastDate: DateTime(2100),
                    );
                    //if 'cancel' => null
                    if (newDate == null) {
                      return;
                    }
                    //if 'ok' => Datetime
                    setState(() => putdate = newDate);
                  },
                ),
                Text(
                  '${putdate.year}/${putdate.month}/${putdate.day}',
                  style: const TextStyle(fontWeight: FontWeight.bold),
                ),
              ],
            ),
            
      actions: [
        TextButton(
          child: const Text('cancel'),
          onPressed: () => Navigator.of(context).pop(),
        ),
        TextButton(
          child: const Text('confirm'),
          onPressed: () {
            debugPrint('print');
            setState(() {});
            Navigator.of(context).pop();
            }
          },
        ),
      ],
    ),
  );
  • you can make another statefull widget to update the value. so the text inside the dialog will auto update every changes – pmatatias Aug 21 '22 at 16:50

1 Answers1

0

something like this. https://stackoverflow.com/a/57240941/12838877

showDialog(
  context: context,
  builder: (context) {
    String contentText = "Content of Dialog";
    return StatefulBuilder(
      builder: (context, setState) {
        return AlertDialog(
          title: Text("Title of Dialog"),
          content: Text(contentText),
          actions: <Widget>[
          ],
        );
      },
    );
  },
);

when you wrap it with StatefullWidget then it will update the widget based on value

pmatatias
  • 3,491
  • 3
  • 10
  • 30