5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Flutter】TextFieldの入力状況をリアルタイムに受け取ってボタンの活性化状態を切り替えたい

5
Last updated at Posted at 2024-08-26

はじめに

表題の件で少々手こずったので記事に残したいと思います。
前提条件として、flutter_hooksというパッケージのuseTextEditingControllerを使用することを前提としています。

記事を執筆時点での筆者の環境


[✓] Flutter (Channel stable, 3.24.1, on macOS 14.5 23F79 darwin-arm64, locale ja-JP)
[✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0)
[✓] Xcode - develop for iOS and macOS (Xcode 15.2)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2023.3)
[✓] VS Code (version 1.92.2)

うまくできていないコード

class HomeScreen extends HookWidget {
  const HomeScreen({
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    // テキストフィールドのコントローラーを作成
    final textController = useTextEditingController(text: '');

    // テキストフィールドのテキストが空でないかどうかを判定
    final isNotEmpty = textController.text.isNotEmpty;

    return Scaffold(
      body: SafeArea(
                // 省略
                TextField(
                  controller: textController,
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: '文字を入力すると登録できます',
                  ),
                ),
                const Gap(50),
                ElevatedButton(
                  // テキストフィールドのテキストが空でない場合のみ登録ボタンを有効にする
                  onPressed: isNotEmpty
                      ? () {
                          final saveText = textController.text;
                          textController.clear();
                          FocusScope.of(context).unfocus();
                          ScaffoldMessenger.of(context).showSnackBar(
                            SnackBar(
                              content: Text('「$saveText」を登録しました'),
                            ),
                          );
                        }
                      : null,
                  child: const Text('登録'),
                ),
                // 省略
うまくいかないコード全体
main.dart
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:gap/gap.dart';

void main() {
  runApp(const MainApp());
}

class MainApp extends StatelessWidget {
  const MainApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: HomeScreen(),
    );
  }
}

class HomeScreen extends HookWidget {
  const HomeScreen({
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    // テキストフィールドのコントローラーを作成
    final textController = useTextEditingController(text: '');

    // テキストフィールドのテキストが空でないかどうかを判定
    final isNotEmpty = textController.text.isNotEmpty;

    return Scaffold(
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 20),
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                TextField(
                  controller: textController,
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: '文字を入力すると登録できます',
                  ),
                ),
                const Gap(50),
                ElevatedButton(
                  // テキストフィールドのテキストが空でない場合のみ登録ボタンを有効にする
                  onPressed: isNotEmpty
                      ? () {
                          final saveText = textController.text;
                          textController.clear();
                          FocusScope.of(context).unfocus();
                          ScaffoldMessenger.of(context).showSnackBar(
                            SnackBar(
                              content: Text('「$saveText」を登録しました'),
                            ),
                          );
                        }
                      : null,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: isNotEmpty ? Colors.blue : Colors.grey,
                  ),
                  child: const Text('登録'),
                ),
                const Gap(80),
                ElevatedButton(
                  onPressed: textController.clear,
                  child: const Text('クリア'),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
useTextEditingControllerのtextが空文字かを判定にしてボタンが活性化するようにしています。

しかし、いくら文字を入力してもこのままだとボタンが活性化になりません。

ここでエンター(レチェックのボタン)をタップすると活性化になります

できれば一文字目から変換が終わってなくても活性化して欲しいところです。
百歩譲ってこれで良かったとしても、よくない点があります。

一度上記の活性化状態後に全部文字を削除ボタンで消して

何も文字がない状態で登録ボタンが押せてしまうのです😇

スクリーンショットの一番下に表示されているスナックバーにもあるとおり、から文字を登録できてしまいました。

解決策: useListenableSelectorを使おう

@override
  Widget build(BuildContext context) {
    // テキストフィールドのコントローラーを作成
    final textController = useTextEditingController(text: '');

    // ❌ これをやめて
    // final isNotEmpty = textController.text.isNotEmpty;

    // テキストフィールドのテキストが空でないかどうかを判定
    // ⭕️ これを使う
    final isNotEmpty = useListenableSelector(
      textController,
      () => textController.text.isNotEmpty,
    );

    return Scaffold(

上記に差し替えるだけで
TextFieldの入力状況をリアルタイムに受け取ってボタンの活性状態を切り替える
機能を実現できます!

考察

useTextEditingController単体ではリアルタイムの変換に対応していないようです。
文字を入力した時点ではWidgetがリビルドされていないのです。
なぜかレチェックのボタンを押すとリビルドされる謎仕様。

そこでuseListenableSelectorを使って状況の変化を受け取ったらリビルドするようにしています。
第一引数に観察対象、第二引数にその観察する変化内容を定義します。
今回で行けば観察対象がuseTextEditingControllerで、
観察する変化内容がuseTextEditingControllerのtextプロパティが空文字か否かです。

終わりに

今回の問題はWidgetTestを書いている時に発覚しました。
いくらテストで文字を入れてもボタンが活性化されなかったのです。
この問題の解決に数時間とかしました🥲

同じ問題を抱える方のお役に立てれば幸いです。

5
2
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
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?