Auto close keyboard in Flutter

flutter

In Flutter, there are several methods to dismiss the keyboard when it’s no longer needed. One of the most effective and straightforward approaches is to create a reusable widget and implement it within the onTap, onPressed, onChanged, etc., callbacks from the beginning. This ensures that the keyboard will automatically close when interacting with these UI elements.

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Dismiss Keyboard Example'),
        ),
        body: Center(
          child: KeyboardDismissExample(),
        ),
      ),
    );
  }
}

class KeyboardDismissExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        // This ensures that tapping anywhere on the screen dismisses the keyboard
        FocusScope.of(context).requestFocus(FocusNode());
      },
      child: Container(
        padding: EdgeInsets.all(20.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TextField(
              decoration: InputDecoration(labelText: 'Enter text'),
            ),
            SizedBox(height: 20.0),
            ElevatedButton(
              onPressed: () {
                firstClosedKeypad();
                //Here you can use remaining logic
              },
              child: Text('Submit'),
            ),
          ],
        ),
      ),
    );
  }
}


//Call this function wherever you wish to automatically dismiss the keyboard within your application.

firstClosedKeypad(){
FocusManager.instance.primaryFocus?.unfocus();
}

Leave a Reply

Your email address will not be published. Required fields are marked *

web_horizontal
About Us ♢ Disclaimer ♢ Privacy Policy ♢ Terms & Conditions ♢ Contact Us

Copyright © 2023 ResearchThinker.com. All rights reserved.