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

weylhg0b  于 2023-03-24  发布在  Flutter
关注(0)|答案(5)|浏览(161)

我试图在我的Flutter应用程序中测试Firestore,但我无法按预期加载数据。
这就是我如何获得数据:

Firestore.instance
        .collection('Test')
        .document('test')
        .get()
        .then((DocumentSnapshot ds) {
          // Use ds as a snapshot

          print('Values from db: $ds');
        });
  • print* 语句输出:

flutter:来自db的值:“DocumentSnapshot”的示例。
我也尝试了以下方法,但没有成功:

Firestore.instance.collection('Test').document('test').get().then((data) {
  // Use ds as a snapshot

  if (data.documentID.length > 0) {
    setState(() {
      stackOver = data.documentID;
      print(stackOver);
    });
  }
});

这里的输出只是 documentID 名称...
那么,如何从Firestore获取字段值?

of1yzvn4

of1yzvn41#

试试这个:

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");
    }
});
yqkkidmi

yqkkidmi2#

我遇到了一个类似的问题,并以这种方式解决了它:

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

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

StreamBuilder<DocumentSnapshot>(
    stream: provideDocumentFieldStream(),
    builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
        if (snapshot.hasData) {
            //snapshot -> AsyncSnapshot of DocumentSnapshot
            //snapshot.data -> DocumentSnapshot
            //snapshot.data.data -> Map of fields that you need :)

            Map<String, dynamic> documentFields = snapshot.data.data;
            //TODO Okay, now you can use documentFields (json) as needed

            return Text(documentFields['field_that_i_need']);
        }
    }
)
bwitn5fc

bwitn5fc3#

空安全码:

  • 一次阅读数据:
var collection = FirebaseFirestore.instance.collection('users');
var docSnapshot = await collection.doc('some_id').get();
if (docSnapshot.exists) {
  Map<String, dynamic> data = docSnapshot.data()!;

  // You can then retrieve the value from the Map like this:
  var name = data['name'];
}
  • 持续监听数据:
var collection = FirebaseFirestore.instance.collection('users');
collection.doc('some_id').snapshots().listen((docSnapshot) {
  if (docSnapshot.exists) {
    Map<String, dynamic> data = docSnapshot.data()!;

    // You can then retrieve the value from the Map like this:
    var name = data['name'];
  }
});
x0fgdtte

x0fgdtte4#

有两种方式:

1.流生成器

当您想要不断地监听更改,并希望数据在没有热重新加载/重新启动的情况下得到更新时

2. FutureBuilder

当您只想获取文档一次,并且不需要不断地监听文档的更改时。

StreamBuilder

1.多个文档

@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: StreamBuilder<QuerySnapshot>(
          stream: FirebaseFirestore
                  .instance.
                  .collection('users') // 👈 Your desired collection name here
                  .snapshots(), 
          builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
            if (snapshot.hasError) {
              return const Text('Something went wrong');
            }
            if (snapshot.connectionState == ConnectionState.waiting) {
              return const Text("Loading");
            }
            return ListView(
                children: snapshot.data!.docs.map((DocumentSnapshot document) {
              Map<String, dynamic> data =
                  document.data()! as Map<String, dynamic>;
              return ListTile(
                title: Text(data['fullName']), // 👈 Your valid data here
              );
            }).toList());
          },
        ),
      ),
    );
  }

2.单文档

@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: StreamBuilder<DocumentSnapshot<Map<String, dynamic>>>(
          stream:  FirebaseFirestore
                   .instance
                   .collection('users')
                   .doc(FirebaseAuth.instance.currentUser!.uid) // 👈 Your document id change accordingly
                   .snapshots(), 
          builder:
              (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
            if (snapshot.hasError) {
              return const Text('Something went wrong');
            }
            if (snapshot.connectionState == ConnectionState.waiting) {
              return const Text("Loading");
            }
            Map<String, dynamic> data =
                snapshot.data!.data()! as Map<String, dynamic>;
            return Text(data['fullName']); // 👈 your valid data here
          },
        ),
      ),
    );
  }

FutureBuilder

1.多文档

@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: FutureBuilder<QuerySnapshot>(
        future: FirebaseFirestore
                .instance
                .collection('users') // 👈 Your collection name here
                .get(), 
        builder: (_, snapshot) {
          if (snapshot.hasError) return Text('Error = ${snapshot.error}');
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Text("Loading");
          }
          return ListView(
              children: snapshot.data!.docs.map((DocumentSnapshot document) {
            Map<String, dynamic> data = document.data()! as Map<String, dynamic>;
            return ListTile(
              title: Text(data['avatar']), // 👈 Your valid data here
            );
          }).toList());
        },
      )),
    );
  }

2.单文档

@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: FutureBuilder<DocumentSnapshot<Map<String, dynamic>>>(
        future: FirebaseFirestore.instance
            .collection('users')
            .doc(FirebaseAuth.instance.currentUser!.uid)  // 👈 Your document id change accordingly
            .get(),
        builder: (_, snapshot) {
          if (snapshot.hasError) return Text('Error = ${snapshot.error}');
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Text("Loading");
          }
          Map<String, dynamic> data = snapshot.data!.data()!;
          return Text(data['fullName']); //👈 Your valid data here
        },
      )),
    );
  }
ws51t4hk

ws51t4hk5#

我在Firestore数据库中有一个用户列表,我需要提取userName信息:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';

FirebaseAuth firebaseAuth = FirebaseAuth.instance;

class Database {
  static String? userName;

  static void showDisplayName() async {
    var collection = FirebaseFirestore.instance.collection('users');
    // userUid is the current authenticated user
    var docSnapshot = await collection.doc(userUid).get();

    Map<String, dynamic> data = docSnapshot.data()!;

    userName = data['displayName'];
  }
}

然后可以调用Database.userName来获取字符串值
下面是我的Firestore示例:

相关问题