flutter

Flutter TextFormField lost focus when showDialog


I have a TextFormField that only allows 20 characters input. If entering more than 20 characters, there will be a prompt using the showDialog and AlertDialog. It's an ephemeral prompt and disappear automatically. Therefore, I don't want the textFormField lost the focus.

The fact is when dialog shows up the focus on TextFormField is lost. Is there a way to keep the focus ?


Solution

  • You should use OverlayEntry or SnackBar instead of showDialog.

    void showOverlay(BuildContext context) {
      final overlay = Overlay.of(context);
      final overlayEntry = OverlayEntry(
        builder: (context) => Positioned(
          top: 100,
          left: 50,
          child: Material(
            color: Colors.transparent,
            child: Container(
              padding: EdgeInsets.all(10),
              color: Colors.black,
              child: Text("Maximum 20 characters!", style: TextStyle(color: Colors.white)),
            ),
          ),
        ),
      );
    
      overlay.insert(overlayEntry);
    
      Future.delayed(Duration(seconds: 2), () {
        overlayEntry.remove();
      });
    }
    
    

    or

    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text("Maximum 20 characters allowed!"))
    );