Download StackFood Multi Restaurant, Food Delivery App with Laravel Admin and Restaurant Panel Buy Full App on $79
Download FlutKit - Flutter UI Kit Most beautiful Flutter UI Kit with 20+ Full App, 450+ Screens. Buy Full Kit on $39
Download Fluxstore Multi Vendor WooCommerce/Dokan Plugin compatible WordPress eCommerce Flutter App. Buy Full App on $79

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. 

How to Get Current Focus Node:

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

How to Dismiss Keyboard by Unfocusing from Current Focused 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
}

Full Code Example:

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"))
               ]
             )
          )
      );
  }
}

Screenshot Output:

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...