Flutter keep keyboard open

Flutter Keep Keyboard Open

By default, Flutter automatically closes the keyboard when a user taps outside of any text input field. However, there may be cases where you want to keep the keyboard open even when the user taps outside of the input field. You can achieve this by using the FocusScope class and managing the focus node manually.

Example

Let’s say we have a simple login form with an email text field and a password text field. We want to keep the keyboard open even if the user taps outside of the text fields:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  final FocusNode _emailFocusNode = FocusNode();
  final FocusNode _passwordFocusNode = FocusNode();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Keep Keyboard Open',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Keep Keyboard Open'),
        ),
        body: Container(
          padding: EdgeInsets.all(16),
          child: Column(
            children: [
              TextFormField(
                decoration: InputDecoration(
                  labelText: 'Email',
                ),
                focusNode: _emailFocusNode,
                autocorrect: false,
                keyboardType: TextInputType.emailAddress,
                textInputAction: TextInputAction.next,
                onFieldSubmitted: (_) {
                  FocusScope.of(context).requestFocus(_passwordFocusNode);
                },
              ),
              TextFormField(
                decoration: InputDecoration(
                  labelText: 'Password',
                ),
                focusNode: _passwordFocusNode,
                obscureText: true,
                textInputAction: TextInputAction.done,
                onFieldSubmitted: (_) {
                  _passwordFocusNode.unfocus();
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}

In the above example, we create two FocusNode instances, _emailFocusNode and _passwordFocusNode. By assigning these focus nodes to the respective text fields, we can manually manage the focus between them.

When the user submits the email field, we request focus on the password field using FocusScope.of(context).requestFocus(_passwordFocusNode);. Similarly, when the user submits the password field, we call _passwordFocusNode.unfocus(); to remove the focus from the field.

This way, even if the user taps outside of the text fields, the keyboard will not automatically close. It will only close when the user explicitly provides an action that unfocuses the password field, like tapping the done button.

Leave a comment