在小部件上方找不到正确的提供者

Could not find correct provider above widget

我对 Flutter 比较陌生,正在构建一个从 API 获取数据并在整个应用程序的不同小部件上显示数据的应用程序。我正在使用 Provider 执行 API 调用并将反序列化的 json 存储在 属性 中,然后我在 initState 函数中访问。下面是我的 main.dart 的小部件树,然后我想访问在仪表板页面中找到的提供程序,因为这是需要值的地方。我知道我做的是错的,但我到底错了多少?

  runApp(MaterialApp(
    home: LoginPage(),
    routes: routes,
  ));
}

class SampleApp extends StatefulWidget {
  @override
  SampleAppState createState() => SampleAppState();
}

class SampleAppState extends State<SampleApp> {
  int currentIndex = 0;
  final List<Widget> childPages = [
    Page1(),
    Page2(),
    Page3(),
    Page4()
  ];

  void onTapped(int index) {
    setState(() {
      currentIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (context) => APIProvider())
      ],
      child: Scaffold(
        body: childPages[currentIndex],
        bottomNavigationBar: BottomNavigationBar(
          onTap: onTapped,
          currentIndex: currentIndex,
          fixedColor: Colors.lightBlue,
          backgroundColor: Colors.white,
          type: BottomNavigationBarType.fixed,
          items: [
            BottomNavigationBarItem(
                icon: new Icon(Icons.dashboard),
                title: new Text('Page 1'),
                activeIcon: new Icon(
                  Icons.dashboard,
                  color: Colors.lightBlue,
                )),
            BottomNavigationBarItem(
                icon: new Icon(Icons.list),
                title: new Text('Page 2'),
                activeIcon: new Icon(
                  Icons.list,
                  color: Colors.lightBlue,
                )),
            BottomNavigationBarItem(
                icon: new Icon(Icons.collections_bookmark),
                title: new Text('Page 3'),
                activeIcon: new Icon(
                  Icons.collections_bookmark,
                  color: Colors.lightBlue,
                )),
            BottomNavigationBarItem(
                icon: new Icon(Icons.person),
                title: new Text('Page 4'),
                activeIcon: new Icon(
                  Icons.person,
                  color: Colors.lightBlue,
                )),
          ],
        ),
      ),
    );
  }
}

然后我尝试访问 Page1 中的提供程序值,如下所示:

@override
  void initState() {
    valueFromProvider =
        Provider.of<APIProvider>(context).providerValue;
    super.initState();
  }

发生这种情况的原因可能是我尝试在 Page1 小部件中访问的提供程序值为空,预加载我的提供程序可以解决这个问题吗?

您没有在正确的时间提供提供商。在您的情况下,您在 page1 添加了 MultiProvider,但您的上下文已经初始化,因此您无法访问它。为了正确访问它,您必须将 MultiProvider 移动到您初始化应用程序的位置,如下所示:

runApp(

MaterialApp(
    home: MultiProvider(
    providers: [
        ChangeNotifierProvider(create: (context) => APIProvider())
      ],
     child:LoginPage()
     ),
    routes: routes,
  ));

这应该可以解决您的问题。