V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Kaco
V2EX  ›  Flutter

Could not find the correct Provider 报错

  •  
  •   Kaco · 2020-10-10 18:54:55 +08:00 · 4150 次点击
    这是一个创建于 1265 天前的主题,其中的信息可能已经有所发展或是发生改变。

    使用的是 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}")),
        );
      }
    
    2 条回复    2020-10-10 19:30:24 +08:00
    kazeik
        1
    kazeik  
       2020-10-10 19:03:46 +08:00 via iPhone
    加个参数 listen:false 试试
    Kaco
        2
    Kaco  
    OP
       2020-10-10 19:30:24 +08:00
    @kazeik 木有用...
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3233 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 14:19 · PVG 22:19 · LAX 07:19 · JFK 10:19
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.