アイコンやラベル付きで文字の入力を促すテキストフィールド

テキストの入力を受け付けるウィジェットはテキストフィールド TextField です。

TextField では入力がある度に onChanged がコールバックされ、 ユーザーの入力が完了した時 (ソフトキーボードを閉じるなど) に onSubmitted がコールバックされます。

下のスクリーンショットを見てもわかるように、ラベル、ヒント、アイコンなどを簡単にキレイに配置しやすくなってます。ラベルのアニメーションなども自動化されてます。

ラベル、ヒント、アイコン、境界線などは、decoration プロパティに、InputDecoration をセットすることで指定します。

上のスクリーンショットを実現するのは、次のコードになります。

import 'package:flutter/material.dart';

void main() => runApp(
      MaterialApp(
        home: MyApp(),
      ),
    );

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _State();
  }
}

class _State extends State<MyApp> {
  String _text = 'Enter something...';

  void _userNameChanged(String value) {
    setState(() {
      _text = 'Changed: $value';
    });
  }

  void _userNameSubmitted(String value) {
    setState(() {
      _text = 'Submitted $value';
    });
  }

  void _passwordChanged(String value) {
    setState(() {
      _text = 'Changed: $value';
    });
  }

  void _passwordSubmitted(String value) {
    setState(() {
      _text = 'Submitted $value';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Input Tests'),
      ),
      body: Container(
        padding: EdgeInsets.all(20),
        child: Column(
          children: <Widget>[
            Text(_text),
            TextField(
              decoration: InputDecoration(
                labelText: 'Username',
                hintText: 'Username',
                icon: Icon(Icons.account_circle),
              ),
              autocorrect: false,
              autofocus: true,
              keyboardType: TextInputType.text,
              onChanged: _userNameChanged,
              onSubmitted: _userNameSubmitted,
            ),
            TextField(
              decoration: InputDecoration(
                labelText: 'Password',
                hintText: 'Password',
                icon: Icon(Icons.security),
              ),
              autocorrect: false,
              autofocus: false,
              keyboardType: TextInputType.text,
              obscureText: true,
              onChanged: _passwordChanged,
              onSubmitted: _passwordSubmitted,
            ),
          ],
        ),
      ),
    );
  }
}

パスワード文字にするには、obscureText プロパティを true にします。

TextField の文字に直ちにアクセスするには、テキストエディッティングコントローラ (TextEditingController) を使うと便利です。

ここまでお読みいただき、誠にありがとうございます。SNS 等でこの記事をシェアしていただけますと、大変励みになります。どうぞよろしくお願いします。

© 2024 Flutter 入門