V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
Kaco
V2EX  ›  Flutter

Could not find the correct Provider 报错

  •  
  •   Kaco · Oct 10, 2020 · 4980 views
    This topic created in 2025 days ago, the information mentioned may be changed or developed.

    使用的是 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 replies    2020-10-10 19:30:24 +08:00
    kazeik
        1
    kazeik  
       Oct 10, 2020 via iPhone
    加个参数 listen:false 试试
    Kaco
        2
    Kaco  
    OP
       Oct 10, 2020
    @kazeik 木有用...
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5584 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 08:40 · PVG 16:40 · LAX 01:40 · JFK 04:40
    ♥ Do have faith in what you're doing.