How to Dismiss Keyboard Programmatically in Flutter

In this example, we are going to show you the easiest way to dismiss the keyboard popup in Flutter. To dismiss the keyboard, we will unfocus from the currently focused widget like TextFiled, TextFormField like input widget. 

FocusScopeNode currentfocus = FocusScope.of(context); //get the currnet focus node

FocusScopeNode currentfocus = FocusScope.of(context); //get the currnet focus node
if (!currentfocus.hasPrimaryFocus) { //prevent Flutter from throwing an exception
    currentfocus.unfocus(); //unfocust from current focust, so that keyboard will dismiss
}

import 'package:flutter/material.dart';
import 'package:get/get.dart';

void main() {
  runApp(
    MaterialApp( 
      home: MyApp()
    )
  );
}

class MyApp extends StatefulWidget{
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
          appBar: AppBar(
              title:Text("Dismiss Keyboard"),
              backgroundColor: Colors.deepOrangeAccent
          ),
          body: Container(
            padding: EdgeInsets.all(15),
             child: Column(
               children:[
                  
                  TextField(),
                  ElevatedButton(
                    onPressed:(){
                         FocusScopeNode currentfocus = FocusScope.of(context); //get the currnet focus node
                         if (!currentfocus.hasPrimaryFocus) { //prevent Flutter from throwing an exception
                              currentfocus.unfocus(); //unfocust from current focust, so that keyboard will dismiss
                          }
                    }, 
                    child: Text("Dismiss Active Keyboard"))
               ]
             )
          )
      );
  }
}

UI output, Keyword will dismiss when clicked on Dismiss button Keyboard popup when focused on TextField

In this way, you can dismiss any active popup keyboard in Flutter App.

No any Comments on this Article


Please Wait...