简体   繁体   中英

Error: Could not find the correct Provider<List<PostModel>> above this ProfileScreen Widget

I'm using firebase firestore to save my data , everything is working until i reach to the point of getting back my data , as soon as i open the screen , it throw an error , i tried to solve it but not sure what is wrong with it , if someone could help thank you .

  • This is the error thrown
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>()),
      }
    ),
  }

  

  • This is my code
 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),
              );
            },
          ),
        ),
      )
    );
  }
}

make sure your ProfileScreen widget is under the builder of provider of List

consider using like this


ChangeNotifierProvider(
  create: (_) => variable,
  Builder: (contex,child)=> ProfileScreen() 
)

or try to use consumer,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM