非同期でサーバーにデータを送った後、ダイアログを閉じるようなケース。
非同期で
await
を入れた所で、Flutterの
ウィジェット
ツリーの再構築が同期されたかは、全くもって保証されない。
そのため、非同期処理後に
Navigator.of(context).pop()
とかやると例外が発生する。
TextButton(
child: const Text("いいえ(エラーになる)"),
onPressed: () async {
await doSomething();
Navigator.pop(context);
At this point the state of the widget's element tree is no longer stable.
To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method
どーするか
公式の推奨は、StatefulWidgetでWidgetのライフサイクルを管理する方式。