Search code examples
flutternavigationtextformfield

TextFormField in flutter pops the page instead of dismissing the keyboard on backbutton


So in my flutter code i have a custom text form field and whenever i try to press back button to dismiss the page it pops that page.

I noticed it only appears if theres a previous page to pop to
if not it simply close the keyboard

I tried setting a will pop scope but didn't work


Solution

  • class MyWidget extends StatelessWidget {
      const MyWidget({super.key});
    
      @override
      Widget build(BuildContext context) {
        return PopScope(
          canPop: false,
          onPopInvoked: (didPop) {
            if (didPop) return;
            if (MediaQuery.of(context).viewInsets.bottom > 0) {
              FocusScope.of(context).requestFocus(FocusNode());
            } else {
              context.pop();
            }
          },
          child: Scaffold(
            appBar: AppBar(),
            body: Placeholder(),
          ),
        );
      }
    }