非同期で取得したテキストを初期値に設定したいの?|TextEditingController|TextFormField|Flutter


TextFormField の初期テキストは「initialValue」に設定するよね。

だけどこれ、例えばデータベースとかサーバからデータを取得した場合、ビルド後に非同期で設定しても無視されちゃう。

initialValue」はビルド時にしか反映されないから、以下みたいな実装とは全く別のアプローチが必要ってこと。

---------
String _text '';

...

setState(() {
  _text = '非同期で取得したテキスト';
}

...

TextFormField(
  initialValue: _text
);
---------

↑これではダメ。


やり方

この件は、ちゃんと「TextFormField」のリファレンスに書いてあった。

When a controller is specified, its TextEditingController.text defines the initialValue. If this FormField is part of a scrolling container that lazily constructs its children, like a ListView or a CustomScrollView, then a controller should be specified. The controller's lifetime should be managed by a stateful widget ancestor of the scrolling container.

If a controller is not specified, initialValue can be used to give the automatically generated controller an initial value.

controllerTextEditingController)」を使うと、遅延(非同期)で実現できる。

---------
final _controller = TextEditingController();

...

setState(() {
  _controller.text = '非同期で取得したテキスト';
}

...

TextFormField(
  controller: _controller,
);
---------

Flutterリファレンスがしっかりしているね!


参照した記事


直近に読んでいた漫画(おすすめ)

コメント

このブログの人気の投稿

ImagePicker を操作すると「Lost connection to device.」とだけ言い残して強制終了するの?|iOS|Flutter

Android SDK バージョン(コンパイルに使用する Android API レベル)を変更するの?|compileSdkVersion|SDK|Android|Flutter