[Flutter]main関数内で非同期処理をする際の注意点(Unhandled Exception: ServicesBinding.defaultBinaryMessenger was accessed before the binding was initialized.の対処法)

こんな感じで、main関数内で非同期処理をしてアプリを回すと、、

 

こんなエラーが出てアプリが落ちてしまいます、、

Unhandled Exception: ServicesBinding.defaultBinaryMessenger was accessed before the binding was initialized.
If you're running an application and need to access the binary messenger before `runApp()` has been called
 (for example, during plugin initialization), then you need to explicitly call the `WidgetsFlutterBinding.ensureInitialized()` first.

 

そんなときは、エラーメッセージにあるように、非同期処理の前で

WidgetsFlutterBinding.ensureInitialized();

を入れてやると解決します。

 

(公式リファレンスはこちら)

Returns an instance of the WidgetsBinding, creating and initializing it if necessary. If one is created, it will be a WidgetsFlutterBinding. If one was previously initialized, then it will at least implement WidgetsBinding.

You only need to call this method if you need the binding to be initialized before calling runApp.

(詳しくは、下の動画で解説していますので、よろしければご覧下さい)

こんな記事も読まれています

おすすめコンテンツ




Flutter(フラッター)


みんプロ作成アプリ




TOP