Как автоматически закрыть клавиатуру во Flutter: несколько методов с примерами кода

Чтобы автоматически закрыть клавиатуру во Flutter, вы можете использовать несколько методов в зависимости от контекста и взаимодействия с пользователем. Вот несколько подходов с примерами кода:

Метод 1: использование метода FocusNodeи unfocus()

import 'package:flutter/material.dart';
class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
  FocusNode _focusNode;
  @override
  void initState() {
    super.initState();
    _focusNode = FocusNode();
    _focusNode.addListener(_onFocusChange);
  }
  @override
  void dispose() {
    _focusNode.removeListener(_onFocusChange);
    _focusNode.dispose();
    super.dispose();
  }
  void _onFocusChange() {
    if (!_focusNode.hasFocus) {
      // Call unfocus() to close the keyboard
      _focusNode.unfocus();
    }
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GestureDetector(
        onTap: () {
          // When the user taps outside the text field, close the keyboard
          _focusNode.unfocus();
        },
        child: Center(
          child: TextField(
            focusNode: _focusNode,
            decoration: InputDecoration(
              hintText: 'Enter text',
            ),
          ),
        ),
      ),
    );
  }
}

Метод 2: использование GestureDetectorи SystemChannels, чтобы скрыть клавиатуру

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GestureDetector(
        onTap: () {
          // When the user taps outside the text field, close the keyboard
          SystemChannels.textInput.invokeMethod('TextInput.hide');
        },
        child: Center(
          child: TextField(
            decoration: InputDecoration(
              hintText: 'Enter text',
            ),
          ),
        ),
      ),
    );
  }
}

Метод 3: использование WillPopScopeдля закрытия клавиатуры при нажатии кнопки «Назад»

import 'package:flutter/material.dart';
class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: WillPopScope(
        onWillPop: () async {
          // Close the keyboard when the back button is pressed
          FocusScope.of(context).unfocus();
          return true;
        },
        child: Center(
          child: TextField(
            decoration: InputDecoration(
              hintText: 'Enter text',
            ),
          ),
        ),
      ),
    );
  }
}