简体   繁体   English

如何使用 Riverpod 包从 Flutter 中的 firebase 集合中获取所有文档?

[英]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>>.我正在使用 provider 包并有一个提供者,它从一个全局变量 idea 中获取其初始值,它是一个 json 数据列表,类型为 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.现在我想要实现的是替换变量idea,而是使用我从firebase上的集合中获得的文档列表。

But I am not sure how to proceed from here onwards.但我不确定如何从这里开始。

Here's a second provider that fetches the snapshot form firestore.这是获取快照表单 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.我的其余代码依赖于 ideaListProvider,所以我必须以某种方式向它提供来自 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.首先,您想要做的很可能是将您的 Firestore 数据映射到您的数据模型。 This can be accomplished by creating a new stream mapped from your firestore data stream:这可以通过创建一个从 Firestore 数据流映射的新流来实现:

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.现在剩下的就是读取您的 StreamProvider。 An example that will handle loading, error, and new data states could be as follows (with hooks_riverpod ):处理加载、错误和新数据状态的示例如下(使用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()),
              );
            },
          );
        },
      ),
    );
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Flutter Riverpod:使用 Riverpod 从 Firebase 获取数据时出现问题 - Flutter Riverpod : Problems fetching data from Firebase using Riverpod 从 Firebase 集合中获取所有文档并设置为静态 var Flutter - Get all documents from a Firebase collection and set to static var Flutter 获取集合中的所有文档 - Firebase Firestore iOS - Fetch all documents in collection - Firebase Firestore iOS Firebase Flutter Riverpod:在使用 Riverpod 跨模型映射值时,如何从 Firebase 获取 documentID? 包含代码 - Firebase Flutter Riverpod: How do I get the documentID from Firebase when using Riverpod to map values across a model? Code Included Flutter - 如何向 firebase 集合中的所有文档添加字段 - Flutter - How to add a field to all documents in firebase collection 如何获取 Firebase 集合中的所有文档(包括不存在的祖先文档)? - How do you fetch all documents (including non-existent ancestor documents) in a Firebase collection? 使用 Firebase 函数从 Firestore 集合中获取所有文档 - Get all documents from Firestore Collection using Firebase Functions 如何从 firebase 中的集合中的所有文档中获取特定数据? - How to get specific data from all documents from a collection in firebase? 如何让用户阅读firebase中documents.uid == user.uid的所有文档的集合 - How to make a user read a collection of all documents where documents.uid == user.uid in firebase flutter 如何在flutter更新firebase的收款文件? - How to update collection documents in firebase in flutter?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM