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?

Flutter 学習メモ(Flutterの基本・例外処理)

Posted at

お願い
本記事の内容に誤りや改善点がございましたら、コメント等でご指摘いただけますと幸いです。
なお、本記事は個人の学習記録として作成したものです。業務でご利用の際は、公式ドキュメントもあわせてご確認ください。

1. はじめに

会社でFlutterを使うことになりましたが、まったくの初心者だったため、学習の一環として気になったFlutterの特徴を整理しました。

補足
Dartの特徴で気になったところは下記の記事でまとめました。
Flutter 学習メモ(Dartの基本仕様)(Java経験者向け)
Flutterのディレクトリ構成、Widgetツリーは下記の記事でまとめました。
Flutter 学習メモ(Flutterの基本・ディレクトリ構成, Widgetツリー)

2. 例外処理

2-1. 基本的な例外処理

  • try-catch
try {
  // 例外が発生する可能性のある処理
  int result = 10 ~/ 0; // ゼロ除算
} catch (e, stackTrace) {
  print('エラーが発生しました: $e');
  print('スタックトレース:');
  print(stackTrace);
} finally {
  // 例外の有無に関わらず実行される処理
  print('処理を終了します');
}

2-2. カスタム例外

Exceptionインターフェースを実装することで、独自の例外クラスを作成できる

class NetworkException implements Exception {
  final String message;
  NetworkException(this.message);

  @override
  String toString() => 'NetworkException: $message';
}

2-3. Flutterが提供する例外処理

  • FlutterError.onError
    UI関連のエラーをキャッチ
void main() {
  FlutterError.onError = (FlutterErrorDetails details) {
    FlutterError.dumpErrorToConsole(details); // デバッグコンソールに出力
    // ログ送信やエラーレポート出力処理など
  };

  runApp(MyApp());
}

  • PlatformDispatcher.instance.onError
    アプリ全体の未処理例外をキャッチ
void main() {
  // Flutterフレームワーク内のエラーをキャッチ
  FlutterError.onError = (FlutterErrorDetails details) {
    FlutterError.dumpErrorToConsole(details);
    // ログ送信やエラーレポート処理など
  };

  // 非同期処理などの未処理例外をキャッチ
  PlatformDispatcher.instance.onError = (Object error, StackTrace stack) {
    print("捕捉した例外: $error");
    print("スタックトレース: $stack");
    return true; // true を返すと再スローされない
  };

  runApp(MyApp());
}

3. サンプルコード

3-1. ディレクトリ構成

lib/
├── c05_exception_ex/                     ← 基本的な例外処理
│     ├── exception_logic.dart            ← 例外処理のロジッククラス
│     ├── main.dart                       ← エントリーポイント
│     └── network_exception.dart          ← カスタム例外 
│
└── c06_flutter_exception_ex/             ← Flutterの例外処理
      ├── exception_logic.dart            ← 例外を発生させる処理
      └── main.dart                       ← エントリーポイント & 例外処理のロジッククラス

3-2. 実行方法

『2-1. 基本的な例外処理』『2-2. カスタム例外』のサンプル (c05_basic_exception_ex)

  1. ターミナルでプロジェクトルートに移動
    cd flutter_sample
    
  2. 実行
    dart run lib\c05_basic_exception_ex\main.dart
    
  3. コンソールに例外処理のログが出力されます。

『2-3. Flutterが提供する例外処理』のサンプル (c06_flutter_exception_ex)

  1. ターミナルでプロジェクトルートに移動
    cd flutter_sample
    
  2. 実行
    flutter run lib\c06_flutter_exception_ex\main.dart
    
  3. アプリが起動したら、ボタンを押す。コンソールに例外処理のログが出力されます。
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?