🧩
Flutter TextFormFieldをclearする二つの方法
もっといろいろあるだろうけど
TextFormFieldに書き込んだ文字が、用が済んでもそこにあるのはイラッとする。
続けてもう一回何か書き込みたかったりしたら、さらにイラッとする。
なので消えていただきましょう。
以下の二種は、私がそういう状況で使った、というだけで、
こういう状況ならこうする、という意味ではありません、ご了承ください。
Formを空にする方法としては右端に×つけておく、というのが簡単かもしれないけれど、
せっかく次の関数を呼ぶボタンがあるので、そこに乗っけます。
検索語をclearして次の検索に備える
左のFormに書き込まれた文字列を使って、右のボタンで検索すると同時にFormをclear
final TextEditingController controller = TextEditingController();
Row(
children: [
Expanded(
flex: 5,
child: Padding(
padding: const EdgeInsets.fromLTRB(20,20,5,20),
child: FormatGrey(
controller: controller,
hintText: "Search Term",
onChanged: (text) {
},
),
),
),
Expanded(
flex: 2,
child: Padding(
padding: const EdgeInsets.fromLTRB(5,20,20,20),
child: ElevatedButton(
onPressed: () {
print("Submitted country: ${controller.text}");
timeline.fetchPrincipal(country: controller.text.isNotEmpty
? controller.text
: null);
showDialog(
barrierDismissible: false,
context: context,
builder: (BuildContext context){
return AlertDialog(
title: const Text('Successfully Selected'),
content: const Text('Choose an Era and Move On'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('OK')),
],
);
});
controller.clear(); <=これで消してる
},
child: const Text("Submit"),
),),
)
入力された単語を保存して、表示して、次の入力を待つ
選択肢をチップで表示していますが、自分で選択肢を追加することもできます。
追加したい単語を書いて、ボタンを押すと、新しいチップができて、同時にFormがclearされます。
final pattKey = GlobalKey<FormFieldState>();
Padding(
padding: const EdgeInsets.all(30.0),
child: TffFormat(
key: pattKey,
hintText: 'a New Place at that time You Want',
onChanged: (text) {
newPlaceatt = text;
},
tffColor1: Colors.black54,
tffColor2: const Color(0x99e6e6fa),
),
),
ButtonFormat(
onPressed: () {
addPlaceATTandFetch();
pattKey.currentState!.reset(); <=これで消してる
},
label:'Add a New Place at that time',
),
同じ仕組みのUIがいくつかあるのに、Sampleに倣ってformKeyを一つだけ設定していたら
「使い回すな!」と叱られました(゚゚)(。。)ペコッ
なので、名前を変えて、いくつか作ってます。
多機能なUI一つで使い回す、というのもアリかと思うけれど、
UX、どちらがいいのか、イマイチわからない。それはまた、別の問題。
Discussion