【问题标题】:Retrieve one field from firebase and display it in a Text Widget从 Firebase 中检索一个字段并将其显示在文本小部件中
【发布时间】:2021-11-19 11:51:08
【问题描述】:

我正在从 firestore 检索用户的名字,将其存储在一个变量中,然后尝试使用文本小部件显示它。 数据库查询肯定有效,因为我打印了它的结果。 另一方面,用于存储数据的变量在 Text 小部件中使用,但它不显示任何内容。

主页.dart

//get the specific document I need
DocumentReference userName = FirebaseFirestore.instance
      .collection('users')
      .doc(FirebaseAuth.instance.currentUser!.uid);

//Variable used to store the name
String firstName = '';

@override
  Widget build(BuildContext context) {
//Get specific field from a document
    userName.get().then((DocumentSnapshot ds) {
      firstName = ds['firstName'];
      print(firstName);
    });
return Scaffold(
      appBar: AppBar(
        title: const Text('Homepage'),
      ),
body: Column(
        children: [
          Padding(
              padding: const EdgeInsets.only(
                top: 20,
              ),
              child: Text(firstName)),

有什么建议吗?

【问题讨论】:

    标签: firebase flutter dart google-cloud-firestore


    【解决方案1】:

    在初始化状态下调用它;否则,您可以使用FutureBuilderStreamBuilder 调用它

      @override
      void initState() {
        super.initState();
        userName.get().then((DocumentSnapshot ds) {
          firstName = ds['firstName'];
          print(firstName);
        });
      }
    
    

    更新

    FutureBuilder<DocumentSnapshot>(
          future: userName.get(),
          builder:
              (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
    
            if (snapshot.hasError) {
              return Text("Something went wrong");
            }
    
            if (snapshot.hasData && !snapshot.data!.exists) {
              return Text("Document does not exist");
            }
    
            if (snapshot.connectionState == ConnectionState.done) {
              Map<String, dynamic> data = snapshot.data!.data() as Map<String, dynamic>;
              return Text("Full Name: ${data['firstName']}");
            }
    
            return Text("loading");
          },
        )
    

    更多内容可以看这篇文章https://firebase.flutter.dev/docs/firestore/usage/

    【讨论】:

    • 它不适用于 initState()。我试过了。
    • 输出是什么?
    • 没有输出,但我注意到如果我刷新它显示的小部件,我是否可以在显示之前刷新页面?
    • 你可以试试setState
    • 成功了,谢谢,我使用了 initState() 和 FutureBuilder
    【解决方案2】:

    在你的 initState 中添加这个

    因此,数据将在构建函数运行之前获取,您可以在 Text 小部件中访问“firstName”

      @mustCallSuper
      void initState()async {
       await DocumentReference userName = FirebaseFirestore.instance
          .collection('users')
          .doc(FirebaseAuth.instance.currentUser!.uid);
    userName.snapshots().listen((snapshot) {
          var firstName = snapshot.docs["firstName"];
           });
        super.initState();
         }
    

    如果您输入完整代码,我将运行代码并在我的模拟器中显示所需的输出

    谢谢

    【讨论】:

    • 我得到一个错误 initState() 返回了一个 future,它必须是 void 没有 async 关键字。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2018-09-25
    • 1970-01-01
    相关资源
    最近更新 更多