[Flutter] Error: Could not find the correct Provider<*> above this ** Widget

김지훈·2023년 9월 6일
0

오류사냥

목록 보기
2/3

Provider로 API서버에서 데이터를 가져와 뿌려주는 페이지가 완성됐다.
이제 다른 페이지에서 이 페이지로 들어갈 수 있게 연결을 시켜줬다.
들어가는 구조는 이렇다.

MyApp(main.dart) → MainPage → MyPage → MyGroup

데이터를 뿌려주는 페이지는 MyGroup이고, MainPage와 MyPage에 있는 버튼을 통해 navigator.push 로 각각의 페이지를 전환시켰다.

그...러..ㄴ...데.....

The following ProviderNotFoundException was thrown building Builder:
Error: Could not find the correct Provider<MyPageProvider$> above this MainMyGroup Widget
This happens because you used a BuildContext that does not include the provider
of your choice.

라고한다.

찾아보니 Provider의 위치 문제였다.

일단 오류가 난 상황의 코드와 Widget Tree는 이렇다.

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        title: '오류싫어잉',
        theme: ThemeData(
          primaryColor: Colors.white,
          scaffoldBackgroundColor: Colors.white,
        ),
        home: MultiProvider(
          providers: [
            ChangeNotifierProvider(create: (context) => MyPageProvider(),),
            ChangeNotifierProvider(create: (context) => OrganizationProvider(),),
            ChangeNotifierProvider(create: (context) => DonationProvider(),),
          ],
          child: MainPage(),
        ));

오류때문에 MyGroup은 안나온 듯 한데, MyPage와 동일한 수준으로 MyGroup이 생길것이다.
그런데 이런 구조라면, 이용하고싶은 MyPageProvider를 못찾는다.
MaterialApp에서 찾게되는데 MyPageProvider는 그 하위에 있기 때문.

그래서 MaterialApp을 MultiProvider보다 하위에 위치하도록 옮겨야 한다고 한다.

수정 결과

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (context) => MyPageProvider(),),
        ChangeNotifierProvider(create: (context) => OrganizationProvider(),),
        ChangeNotifierProvider(create: (context) => DonationProvider(),),
      ],
      child: MaterialApp(
      debugShowCheckedModeBanner: false,
      title: '아싸됐다',
      theme: ThemeData(
        primaryColor: Colors.white,
        scaffoldBackgroundColor: Colors.white,
      ),
      home: MainPage(),
      )
    );

위젯트리에서 볼 수 있듯이 MaterialApp 상위에 Provider들이 존재한다.
데이터 호출도 성공했다.

약간 그런 느낌인것같다.

친구한테 돈빌리고싶어서 찾아갔는데..
→자식에게 돈이 있어서 빌리기 실패.
vs
→친구의 부모님이 갖고계신 돈을 친구도 쓸 수 있어서 빌리기 성공.

맞겠ㅈ...
ㅇ..아닌가...

0개의 댓글