如何从扑扑的Firestore文档字段中获取数据?

时间:2019-07-18 11:56:38

标签: firebase flutter dart google-cloud-firestore

我正在尝试在flutter-app中测试firestore,但无法真正按预期加载数据。

这是我获取数据的方式:

InputStream

和打印语句输出:flutter:来自db的值:'DocumentSnapshot'的实例。

我也尝试了以下尝试,但没有成功:

getCacheDir()

这里的输出仅是documentID名称。

那么,我怎么能从firestore中获取字段值?

最诚挚的问候!

3 个答案:

答案 0 :(得分:3)

你好吗?我遇到了类似的问题,并以此方式解决了该问题:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.SpaServices.Webpack;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Mvc;

using OptionsAPI.Services;

namespace OptionsAPI
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            var connectionString =
               "Server=xxx.xx.xx.xxx;Integrated Security=false;Trusted_Connection=false;Database=Options;User Id=xxx;Password=xxxxx";
               services.AddDbContext<OptionsDbContext>(o =>
                   o.UseSqlServer(connectionString));

            services.AddMvc();
            services.AddMvc(option => option.EnableEndpointRouting = false);    
        }

        //etc...

之后,我使用StreamBuilder来使用上面创建的方法:

Stream<DocumentSnapshot> provideDocumentFieldStream() {
    return Firestore.instance
        .collection('collection')
        .document('document')
        .snapshots();
}

答案 1 :(得分:1)

尝试一下:

final String _collection = 'collectionName';
final Firestore _fireStore = Firestore.instance;

getData() async {
  return await _fireStore.collection(_collection).getDocuments();
}

getData().then((val){
    if(val.documents.length > 0){
        print(val.documents[0].data["field"]);
    }
    else{
        print("Not Found");
    }
});

答案 2 :(得分:0)

空安全码:

  • 一次读取数据:

    var collection = FirebaseFirestore.instance.collection('Test');
    var docSnapshot = await collection.doc('test').get();
    if (docSnapshot.exists) {
      Map<String, dynamic>? data = docSnapshot.data();
    
      // You can then retrieve the value from the Map like this:
      var value = data?['your_field'];
    }
    
  • 持续监听数据:

    var collection = FirebaseFirestore.instance.collection('Test');
    collection.doc('test').snapshots().listen((docSnapshot) {
      Map<String, dynamic>? data = docSnapshot.data();
      if (docSnapshot.exists) {
        Map<String, dynamic>? data = docSnapshot.data();
    
        // You can then retrieve the value from the Map like this:
        var value = data?['your_field'];
      }
    });