fluttershowdialogtext-widgetflutter-onpressed

When i input the text in showDialog function and pass it to Text widget it isn't getting displayed


I made a showMyDialog.dart file which contains the showDialog Widget with AlertDialog and inside i used a Textfield to get input from the user to display it on the same Screen after onPress.

I want to display in this ContainerThis is the AlertBox

After the input it should be displayed on the Screen but it didn't i tried to print when state changed and the value is visible in debug Console

Here is the code of showMyDialog.dart :

      import 'package:flutter/material.dart';

      Future<String?> showMyDialog(
        BuildContext context,
        String title,
      ) async {
        TextEditingController _textController = TextEditingController();
        return showDialog<String>(
            context: context,
            builder: (BuildContext context) {
              return AlertDialog(
                title: Text(title),
                content: TextField(
                  controller: _textController,
                  textInputAction: TextInputAction.done,
                ),
                actions: <Widget>[
                  TextButton(
                      onPressed: () {
                        Navigator.of(context).pop(_textController.text);
                      },
                      child: const Text("Ok")),
                      TextButton(
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                      child: const Text("Cancel"))
                ],
                
              );
            });
      }

Here is the code for where i used this :

      String _tempval = "";
      GestureDetector(
          onTap: () async {
            final enteredtext = await showMyDialog(
              context,
              "Add Temperature",
            );
            setState(() {
              _tempval = enteredtext ?? "";
              print(_tempval);
            });
            },
      child: Container(
        width: 120,
        height: 40,
        alignment: Alignment.center,
        padding: const EdgeInsets.symmetric(horizontal: 10),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,children: [
            Text(_tempval),
            const SizedBox(
            width: 6,
            ),
          ],
        ),
      decoration: BoxDecoration(
          border: Border.all(width: 0.4),
          borderRadius:
          const BorderRadius.all(Radius.circular(8))),
        ),
      ),

Solution

  • The _tempval variable is reset to empty once the build function is executed, such as calling setState. The issue will be solved if you declare that variable out of the build function.
    Hope this helps.