1
1

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】WidgetBindingを使ってbuild実行中のページ遷移を防ぐ

Posted at

はじめに

ページ遷移を実装したところ、navigator.dart':Failed assertion: line 5295 pos 12: '!_debugLocked':is not true.というエラーが出ました。解決したので記事にしようと思います。

エラー内容

以下のコードを実行したところ、navigator.dart':Failed assertion: line 5295 pos 12: '!_debugLocked':is not true.というエラーが出ました。

Widget build(BuildContext context) {
		/*--省略--*/
    if (isAccountBanned) {
      Navigator.push(context, AccountBannedPage.route());
      return const SizedBox.shrink();
    } 

このコードにおける問題はbuildメソッド内で直接Navigator.push()を呼び出していることにありました。buildメソッドはウィジェットの描画に関わるため、このメソッド内で直接ページ遷移を行うと、フレームの描画が完了する前に遷移が始まることで状態が不整合になり、エラー(ロック状態)になってしまいます。

解決

以下のようにNavigator.pushWidgetsBinding.instance.addPostFrameCallbackで囲むと解決しました。これにより、フレームワークの描画が完了した後に遷移を実行することができます。WidgetBindingとは公式にも書かれている通り、FlutterEnginとFlutterFrameworkを通信できるようにする役割があります。他にも色々種類があるそうなので後に調べてみようと思います。

Widget build(BuildContext context) {
		/*--省略--*/
  WidgetsBinding.instance.addPostFrameCallback((_) {
    if (isAccountBanned) {
      Navigator.push(context, AccountBannedPage.route());
    }
  });

最後に

このエラーに出会ったことでFlutter自身のロジックについて興味を持つきっかけになりました。これから色々と調べて、確信を持ってコーディングやデバッグのできるエンジニアになりたいと思いました。

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?