Could not find the correct Provider 报错
資深大佬 : Kaco 7
使用的是 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)