こんにちは!本記事では、Provider()を使用したときに出てくるエラーについて解決方法をご紹介します。
エラー文は以下の通り。
The following ProviderNotFoundException was thrown building MyApp(dirty):
Error: Could not find the correct Provider<> above this MyApp Widget
This happens because you used a ‘BuildContext’ that does not include the provider of your choice.
There are a few common scenarios:….

そして画面が左のように真っ赤になると思います。画面に書かれているのはエラー文です。
つまるところ、Provider()を使用してるけど使おうとしてるClassの上位にProviderの宣言書かれてないよ。って言ってます。
目次
解決方法
ChangeNotifierProvider<>()
を、変数を使いたいClassの上位に挿入する。
例えば、下のようにMyApp内でChangeNotifierProvider<>()
を宣言し、その中にPage1、Page1の中にPage2, Page3がある場合を考えます。
この場合は、MyApp()でKのクラスの変数は使うことができません。ただ、Page1()、Page2()、Page3()は使うことができます。

従って、もしProviderがうまく使えない場合は、上位のクラスを作るか、上位のクラスにProviderを宣言し直すようにしましょう。
関連記事
Provider()に関する記事はこちら
あわせて読みたい


【Flutter】Provider()使い方、サンプルコード
こんにちは!本記事では、Provider()というウィジェットについて、サンプルコードを用いながら実践的に説明しています。 Provider()とは Provider()はパッケージの一つ...
コメント