LoginSignup
5
3

More than 3 years have passed since last update.

Navigator operation requested with a context that does not include a Navigator.エラーの原因

Posted at

はじめに

ページ遷移を実装したかったのですが、以下のエラーに遭遇
原因がcontextの理解にも役立つ内容だったためメモとして残す

Navigator operation requested with a context that does not include a Navigator.

原因の解明

参照した記事

エラーは何を言ってるか

Navigator operation requested with a context that does not include a Navigator.
直訳:Navigatorを実行する際にNavigatorを含まないcontextを要求しました。

要は、「context内に必要なNavigatorウィジェットがないよ」と言っている

エラーの原因は何か

Navigator.of(context)が発動すると、対象のcontextからさかのぼって、Navigatorウィジェットを探す

Navigatorウィジェットを含むウィジェットは以下、
MaterialApp
WidgetApp

つまり、Navigator.of(context)の現在地より上にNavigatorウィジェットをもったウィジェットが存在していないとエラーが出る

ちなみに、Navigator.of(context)は「引数に与えた文脈におけるNavigator」の意味
よって、その文脈の中からNavigatorを探さなくてはいけない

そもそもcontextとは何か

「BuildContext context」と書くことから明らかな通り、contextはBuildContextである
builderで使われるこのcontextにはそれ以前に生成されたウィジェットの情報が入っている(正式にはcontextはElementでWidgetツリーを参照している、という状態らしい)
あるbuilder内で使われるcontextには、そのbuilder以前に作られたWidgetツリーの情報が入っており、そのツリー内の情報にはアクセスできる

改めて原因を整理

  • Navigator.of(context)は、すでに作成されているWidgetツリーの中からNavigatorを探してね、という指示である
  • contextはすでに生成されているWidgetツリーの情報である
  • すでに生成されているWidgetツリーの中にNavigatorを含むMaterialAppまたはWidgetAppがなかったため、エラーとなった
  • 自分の場合、contextには、StatelessWidgetしか含まれていない状態であった

解決方法

builderを一段階増やして、WidgetツリーがNavigator持つようにすればよい

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