Home > Mobile >  flutter Text doesnot update after showDatePicker date is selected
flutter Text doesnot update after showDatePicker date is selected

Time:06-06

I couldnot change a text of a Text widget after the date is selected. I have wrapped the Text Widget in a gesture detector and a tap the date picker will start but after selecting a date it wont apply the selected date to the Text field.

The Text Widget is in an Alert Dialog, could that be the reason? Should the showDatePicker and the showDialog widget which wrapped the alert dialog be on the same context?

below here is mu date picker function

  void _showDatePicker() {
    showDatePicker(
            context: context,
            initialDate: DateTime.now(),
            firstDate: DateTime(2021),
            lastDate: DateTime(2023))
        .then((value) {
      setState(() {
        dateTime = value!;
      });
    });
  }

And use case inside widget

GestureDetector(
  onTap: () {
    _showDatePicker();
  },
  child: Text(
    dateTime.toString(),
    style: const TextStyle(
      color: Colors.grey,
      fontSize: 18,
    ),
  ),
),

CodePudding user response:

SetState doesn't work in alert box. Try wrapping the alert dialog with statefulBuilder. That should allow you to do setstate

CodePudding user response:

You need to use StatefulBuilder's setState to update dialog UI, Therefor I am passing this setState to _showDatePicker.

  _showDialog() async {
    await showDialog(
        context: context,
        builder: (context) {
          return StatefulBuilder(
            /// you need to use `StatefulBuilder`'s setState to update dialog ui
            // therefor I am passing this setState to `_showDatePicker`
            builder: (context, setState) => AlertDialog(
              content: GestureDetector(
                onTap: () {
                  _showDatePicker(setState);
                },
                child: Text(
                  dateTime.toString(),
                  style: const TextStyle(
                    color: Colors.grey,
                    fontSize: 18,
                  ),
                ),
              ),
            ),
          );
        });
  }

  DateTime? dateTime;

  void _showDatePicker(setState) async {
    await showDatePicker(
            context: context,
            initialDate: DateTime.now(),
            firstDate: DateTime(2021),
            lastDate: DateTime(2023))
        .then((value) {
      setState(() {
        dateTime = value!;
      });
    });
  }
  • Related