简体   繁体   中英

How to fetch all documents from a firebase collection in Flutter using the Riverpod package?

I am using the provider package and have a provider that gets its initial value from a global variable idea which a list of json data and is of type List<Map<String, dynamic>>.

following is the code for that, which is working expected.

final ideasListProvider = StateNotifierProvider<IdeaList>((ref) {
  return IdeaList([for (var i in ideas) Idea.fromJson(i)]);
});

Now what I am trying to achieve is replace the variable idea and instead use the list of documents I get from a collection I have on firebase.

But I am not sure how to proceed from here onwards.

Here's a second provider that fetches the snapshot form firestore.

final firbaseIdeaProvider = StreamProvider.autoDispose((ref) {
  return FirebaseFirestore.instance.collection('ideas').snapshots();
});

What do I do now? The rest of my code is depended on the ideasListProvider, so I will have to somehow provide it with the a list of the documents from the ideas collection on firebase.

Good news, you are on the right track. First, what you want to do is likely map your firestore data to your data model. This can be accomplished by creating a new stream mapped from your firestore data stream:

final firebaseIdeaProvider = StreamProvider.autoDispose<List<Idea>>((ref) {
  final stream = FirebaseFirestore.instance.collection('ideas').snapshots();
  return stream.map((snapshot) => snapshot.docs.map((doc) => Idea.fromJson(doc.data())).toList());
});

Now all that's left is to read your StreamProvider. An example that will handle loading, error, and new data states could be as follows (with hooks_riverpod ):

class IdeasExample extends HookWidget {
  const IdeasExample({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Ideas Example'),
      ),
      body: useProvider(firebaseIdeaProvider).when(
        loading: () => const Center(child: CircularProgressIndicator()),
        error: (err, stack) => Center(child: Text(err.toString())),
        data: (ideas) {
          return ListView.builder(
            itemCount: ideas.length,
            itemBuilder: (_, index) {
              return ListTile(
                title: Text(ideas[index].toString()),
              );
            },
          );
        },
      ),
    );
  }
}

Without hooks:

class IdeasExample extends ConsumerWidget {
  const IdeasExample({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context, ScopedReader watch) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Ideas Example'),
      ),
      body: watch(firebaseIdeaProvider).when(
        loading: () => const Center(child: CircularProgressIndicator()),
        error: (err, stack) => Center(child: Text(err.toString())),
        data: (ideas) {
          return ListView.builder(
            itemCount: ideas.length,
            itemBuilder: (_, index) {
              return ListTile(
                title: Text(ideas[index].toString()),
              );
            },
          );
        },
      ),
    );
  }
}

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