0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Flutter】ダイアログを閉じた後に何かの処理をしたい時

Posted at

仕事で実装したので記録として残します。

【環境】

Flutter 3.7.7
Dart 2.19.4

【やりたい事】

ログインをした後にHomeを表示する。
この時にAPI(A)を叩いて、DBにデータがあればAPI(B)を叩く。
もしデータが無ければダイアログ(DialigPage)を表示してDBにデータを格納する。
ダイアログが閉じられたら再度API(A)を叩いてデータの有無を確認し、データがあればAPI(B)叩く、データが無ければ再度ダイアログを表示する流れです。

【サンプル】

home_page.dart
class HomePage extends StatefulWidget {

}

class _HomePage extends State<HomePage> {

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


  Future _apiA() async {
    // apiの取得処理 コードは省きます。
    if(データがなかった時){
      _showDialog(context);
    } else {
      await _apiB();
    }
 }

   _apiB() async {
    // apiの取得処理
 }

   _showDialog(BuildContext context) {
       showGeneralDialog(
       context: context,
       barrierDismissible: true,
       barrierColor: Colors.red,
       barrierLabel: MaterialLocalizations.of(context).closeButtonLabel,
       transitionDuration: const Duration(milliseconds: 200),
       pageBuilder: (BuildContext buildContext, Animation animation,
            Animation secondaryAnimation) {
            return DialogPage();
            }).then((value) {
                //ここで再度APIを叩く
                _apiA();
            });
       }
  }

Dialog_page.dart
class DialogPage extends StatefulWidget {

}

class _DialogPage extends State<DialogPage> {

   /*記述を省略
     DBにデータを格納後にpopで戻る*/
   Navigator.of(context).pop(true);
}

【解説】

showGeneralDialog内でDialogPageを表示しています。そして、showGeneralDialogが閉じられた後に _apiAメソッドを呼び出していることがわかります。
このようにすることで、_showDialogメソッド内でダイアログを表示し、ダイアログが閉じられた後に_showDialogメソッドを呼び出してAPIを実行することができます。
これにより、ダイアログとAPIのフローを制御し、APIの実行後に適切な処理を行うことができます。

【最後に】

今回はAPIですが他の処理も実行できますので、ダイアログを閉じた後に何かをしたい時の参考にして頂ければと思います。
最後までご覧頂きありがとう御座いました。
誰かのお役に立てれば幸いです。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?