导入Flutter NFCManager示例仓库作为依赖时遇Provider错误求助
在Flutter项目中使用nfcmanager,导入官方示例的Fork仓库作为依赖复用TagReadPage类时,出现Provider相关错误。
跳转代码:
Navigator.push(context, MaterialPageRoute(builder: (context) => TagReadPage()));
TagReadPage关键代码:
class TagReadPage extends StatelessWidget { static Widget withDependency() => ChangeNotifierProvider<TagReadModel>( create: (context) => TagReadModel(), child: TagReadPage(), ); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Tag - Read')), body: ListView( padding: EdgeInsets.all(2), children: [ FormSection( children: [ FormRow( title: Text('Start Session', style: TextStyle( color: Theme.of(context).colorScheme.primary)), onTap: () => startSession( context: context, handleTag: Provider.of<TagReadModel>(context, listen: false) .handleTag, ), ), ], ), Consumer<TagReadModel>(builder: (context, model, _) { final tag = model.tag; final additionalData = model.additionalData; if (tag != null && additionalData != null) return _TagInfo(tag, additionalData); return SizedBox.shrink(); }), ], ), ); } }
App内报错内容:
Error: Could not find the correct Provider
above this Consumer Widget This happens because you used a 'BuildContext' that does not include the provider of your choice. There are a few common scenarios:
You added a new provider in you main.dart and performed a hot reload, to fix perform a hot restart
The provider you are trying to read is in a different route
Providers are scoped so if you insert of provider inside a route, then other routes will not be able to access that provider
You used a BuildContext that is an ancestor of the provider you are trying to read
Make sure than Consumer
us under your MultiProvider/Provider , this usually happens when you are creating a provider and trying to read it immediately For example, instead of:
Widget build(BuildContext context){
return Provider(
create:(_)=>Example(),
child: Text(context.watch().toString()),)} Consider using builder like so:
Widget build(BuildContext context){
return Provider(
create:(_)=>Example(),
return Text(context.watch().toString()
已执行热重启,问题仍未解决。
问题核心是:你跳转时直接实例化了TagReadPage,但页面内部的Consumer和Provider.of需要ChangeNotifierProvider<TagReadModel>提供的实例,而当前上下文里没有这个Provider。
注意到TagReadPage已经写好了withDependency()静态方法,它已经帮你把页面包裹在对应的Provider中,只需要修改跳转代码,用这个方法创建页面即可:
Navigator.push(context, MaterialPageRoute(builder: (context) => TagReadPage.withDependency()));
这样页面内部的组件就能找到TagReadModel实例,错误即可解决。
内容的提问来源于stack exchange,提问作者reduecto

