Could not find the correct Provider 报错

2020-10-10 18:54:55 +08:00
 Kaco

使用的是 Provider4.3.2

根据教程在 main 中引入 Provider

void main() {
  //强制竖屏
  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])
      .then((_) {
    runApp(MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (context) => Counter()),
        ChangeNotifierProvider(create: (context) => CartProvider()),
      ],
      child: MyApp(),
    ));
  });
}

首页是用 PageView 切换四个页面分别是:首页-分类-购物车-我的 在首页-分类 下使用

final counter = Provider.of<Counter>(context);

会报错 Error: Could not find the correct Provider<Counter> above this CategoryPage Widget

而 购物车-我的 这两个页面则不会,这两个页面是空白的,尝试吧代码复制给首页-分类都依然报错

Widget build(BuildContext context) {
    final counter = Provider.of<Counter>(context);
    final cart = Provider.of<CartProvider>(context);

    return Scaffold(
      appBar: AppBar(
        elevation: 0, // 隐藏阴影
        title: Text("我的"),
      ),
      body: Center(child: Text("${counter.count}")),
    );
  }
4181 次点击
所在节点    Flutter
2 条回复
kazeik
2020-10-10 19:03:46 +08:00
加个参数 listen:false 试试
Kaco
2020-10-10 19:30:24 +08:00
@kazeik 木有用...

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/713761

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX