15
3

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でアプリ開発をしている際、もちろん基本的にはtry-catchでエラーハンドリングをしたり、場合によってはExceptionクラスを自作してうまくエラーハンドリングをすることが好ましいです。

しかし、場合によっては想定外のバグであったり、try-catchを指定していない箇所のバグが発生した場合、デバッグモードだと真っ赤な画面になりますね。

リリースモードだと、時にはアプリがフリーズしたりクラッシュしてしまいます。

そのような想定外エラーの対応として、Firebase CrashlyticsやSentryのサービスを用いてエラーログを収集することも大切です。

今回の記事では、想定外エラーが出た場合に共通エラーダイアログを表示させる小ネタの紹介です。

実装

void main() {
  FlutterError.onError = (FlutterErrorDetails details) {
    FlutterError.dumpErrorToConsole(details);
    runApp(UnexpectedErrorDialog(details));
  };
  runApp(MyApp());
}
class CustomErrorWidget extends StatelessWidget {
  final String errorMessage;

  CustomErrorWidget({this.errorMessage});

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.error_outline,
            color: Colors.red,
            size: 50.0,
          ),
          SizedBox(height: 10.0),
          Text(
            'Error Occurred!',
            style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold),
          ),
          SizedBox(height: 10.0),
          Text(
            errorMessage,
            textAlign: TextAlign.center,
            style: TextStyle(fontSize: 16.0),
          ),
          SizedBox(height: 10.0),
          ElevatedButton(
            // goRouterなど使っている場合、initialRouteに遷移などして対策
            // popでも良い
            onPressed: () => context.goNamed(
              context,
              TopPage.routeName,
            ),
            child: const Text('OK'),
          ),
        ],
      ),
    );
  }
}

ただ、繰り返しですが基本はtry-catchでエラーハンドリングができることが好ましいです。
後日、Exceptionクラスを定義したエラーハンドリングの記事を作成したいと思います。

15
3
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
15
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?