dart flutter中如何从firestore文档字段中获取数据?

kx1ctssn  于 2023-01-18  发布在  Flutter
关注(0)|答案(5)|浏览(148)

我试着在flutter-app中测试firestore,但是我不能像预期的那样加载数据。
我是这样得到数据的:

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

      print('Values from db: $ds');
    });

和打印语句输出: Flutter :db值:“文档快照”的示例。
我也试着遵循,但没有成功:

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

此处的输出仅为文档ID名称。
那么,我怎样才能从firestore得到字段值呢?
最好的问候!

2wnc66cl

2wnc66cl1#

试试这个:

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

j5fpnvbx2#

我也遇到过类似的问题,我是这样解决的:

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']);
        }
    }
)
z4bn682m

z4bn682m3#

空安全代码:

  • 一次阅读数据:
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'];
  }
});
9lowa7mx

9lowa7mx4#

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

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 auth user
    var docSnapshot = await collection.doc(userUid).get();

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

    userName = data['displayName'];
  }
}

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

c9x0cxw0

c9x0cxw05#

有两种方式:

1.流生成器

当您希望不断听取更改,并希望数据在不进行热重新加载/重新启动的情况下得到更新时

2.未来构建者

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

流生成器

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
          },
        ),
      ),
    );
  }

未来建筑师

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
        },
      )),
    );
  }

相关问题