2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Flutter TextField以外の場所をタップしたときに自動的にキーボードを閉じる

Posted at

はじめに

TextField以外の場所をタップしたときに自動的にキーボードを閉じる動きはあらゆる場面で必要ですよね。
そのために汎用的に使えるクラスを作ってみました!

FocusScopeを使ってUnFocusクラスを作る

もう早速コピペを貼ります

lib/views/pages/widgets/un_focus.dart
import 'package:flutter/material.dart';


class UnFocus extends StatelessWidget {
  const UnFocus({
    super.key,
    required this.child,
  });

  final Widget child;
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        // 現在のフォーカス情報を取得
        final currentScope = FocusScope.of(context);
        // hasPrimaryFocusがfalseで、かつhasFocusがtrueであれば、現在何らかのウィジェットがフォーカスを持っていると判定
        if (!currentScope.hasPrimaryFocus && currentScope.hasFocus) {
          // TextFieldなどに設定されているフォーカスが解除され、キーボードが閉じる
          currentScope.unfocus();
        }
      },
      child: child,
    );
  }
}

あとはフォームなのが存在するウィジェットをUnFocusでラップするとOK
最初に見せた動画の場合はScaffoldごとラップしてます!

import 'package:h_calender/views/pages/widgets/un_focus.dart';

class DayPage extends ConsumerWidget {
  const DayPage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return UnFocus(
      child: Scaffold(
          appBar: AppBar(
            title: const Text('記録しよう'),
          ),
          body: ListView(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            children: const [
              _TitleField(),
              SizedBox(height: 24),
              _MemoField(),
              SizedBox(height: 24),
              _SubmitButton(),
            ],
          )),
    );
  }
}
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?