LoginSignup
0
0

More than 1 year has passed since last update.

【Flutter】TextFieldのHintTextを常時表示する

Last updated at Posted at 2022-07-12

ヒントテキストをテキスト入力に合わせてゴニョゴニョしたい

ヒントテキストを使って気の利いたUIを作りたい。
ただ、Flutter標準のTedtFieldだと、テキスト入力があるとHintTextは消えてしまう。
常時表示が出来ない。

だったら、ダミーのTextを上から被せてみよう。
さらに、テキスト同士が重ならないように、テキスト入力に合わせて、ヒントテキストもオフセットさせる。

作ってみた

スクリーンショット 2022-07-12 23.01.21.png
簡単に実装してみたら、イイ感じ。
あとはゴニョゴニョするだけ♪

DatPadで動作確認できます。

ソース

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: Scaffold(
        appBar: AppBar(title: const Text(_title)),
        body: Center(
          child: InputDecoratorExample(),
        ),
      ),
    );
  }
}

class InputDecoratorExample extends StatefulWidget {
  @override
  InputDecoratorExampleState createState() => InputDecoratorExampleState();
}

class InputDecoratorExampleState extends State<InputDecoratorExample> {
  TextEditingController _textController = TextEditingController();
  String inputText = '';

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        TextField(
          controller: _textController,
          decoration: InputDecoration(
            border: OutlineInputBorder(),
          ),
          onChanged: (value) {
            setState(() {
              inputText = value;
            });
          },
        ),
        IgnorePointer(
          child: SizedBox(
            height: 50,
            child: Align(
              alignment: Alignment.centerLeft,
              child: Row(
                children: [
                  SizedBox(width: 12),
                  Opacity(
                    opacity: 0,
                    child: Text(
                      inputText,
                      style: TextStyle(
                        color: Colors.grey[600],
                        fontSize: 16.0,
                      ),
                    ),
                  ),
                  if (inputText != '') SizedBox(width: 6),
                  Text(
                    'Name',
                    style: TextStyle(
                      color: Colors.grey[500],
                      fontSize: 16.0,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }
}
0
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
0
0