如何解决错误:无法在此 ProfileScreen 小部件上方找到正确的 Provider<List<PostModel>>
我正在使用 firebase firestore 来保存我的数据,一切正常,直到我达到取回数据的程度为止,一旦我打开屏幕,它就会抛出错误,我试图解决它但不确定有什么问题,如果有人可以帮忙谢谢。
- 这是抛出的错误
Make sure that ProfileScreen is under your MultiProvider/Provider<List<PostModel>>.
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<Example>(
create: (_) => Example(),// Will throw a ProviderNotFoundError,because `context` is associated
// to the widget that is the parent of `Provider<Example>`
child: Text(context.watch<Example>()),),}
consider using `builder` like so:
Widget build(BuildContext context) {
return Provider<Example>(
create: (_) => Example(),// we use `builder` to obtain a new `BuildContext` that has access to the provider
builder: (context) {
// No longer throws
return Text(context.watch<Example>()),}
),}
- 这是我的代码
class ProfileScreen extends StatefulWidget {
const ProfileScreen({Key? key}) : super(key: key);
@override
_ProfileScreenState createState() => _ProfileScreenState();
}
class _ProfileScreenState extends State<ProfileScreen> {
PostService postService = new PostService();
@override
Widget build(BuildContext context) {
List<PostModel> posts = Provider.of<List<PostModel>>(context);
return StreamProvider<List<PostModel>>.value(
value: postService.getPosts(FirebaseAuth.instance.currentUser!.uid),initialData: [],child: Scaffold(
appBar: AppBar(
title: Text('Posts'),backgroundColor: Colors.blue,body: Container(
child: ListView.builder(
itemCount: posts.length,itemBuilder: (context,index){
return ListTile(
title: Text(posts[index].creator),subtitle: Text(posts[index].text),);
},)
);
}
}
解决方法
确保您的 ProfileScreen 小部件位于 List 提供者的构建器下
考虑这样使用
ChangeNotifierProvider(
create: (_) => variable,Builder: (contex,child)=> ProfileScreen()
)
或尝试使用消费者,
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。