🙌

Flutterで前の画面に戻る前に特定の処理を挟む方法

2022/09/02に公開

TLDR

Flutterで前の画面へ戻る前になんらかの処理を挟みたい場合は戻るボタンを任意の物に書き換えるか、WillPopScopeコンポーネントを使うと良い

WillPopScopeコンポーネントを使う場合

class MyPage extends StatelessWidget {
  const MyPage({Key? key}) : super(key: key);

  
  Widget build(BuildContext context) {
    return WillPopScope( // WillPopScopeコンポーネントで囲う
      onWillPop: () async {
        // ここで任意の処理
        return true; // trueを返すと前の画面へ遷移
      },
      child: Scaffold(
        appBar: AppBar(
          title: const Text('My page'),
        ),
        body: // 省略
      ),
    );
  }
}

戻るボタンを任意の物に変更する場合

class MyPage extends StatelessWidget {
  const MyPage({Key? key}) : super(key: key);

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false, // 自動で生成される戻るボタンを無効化
        leading: const BackButton(), // 作成したボタンを無効化した戻るボタンの変わりに設定
        title: const Text('My Page'),
      ),
      body: // 省略
    );
  }
}

class BackButton extends StatelessWidget {
  const BackButton({Key? key}) : super(key: key);

  
  Widget build(BuildContext context) {
    return TextButton(
      child: const Text(
        '<',
        style: TextStyle(
          color: Colors.white,
          fontWeight: FontWeight.bold,
          fontSize: 12.0,
        ),
      ),
      onPressed: () {
        // ここで任意の処理
        Navigator.of(context).pop(); // 前の画面へ遷移
      },
    );
  }
}
GitHubで編集を提案

Discussion