簡體   English   中英

我無法從雲 firestore 訪問文檔字段並在 flutter 中的 statefulwidget class 中顯示它

[英]I am unable to access document field from cloud firestore and show it in a statefulwidget class in flutter

我想訪問當前登錄用戶的 uname 字段。 我在注冊屏幕中添加了 uname,如下所示:

 onPressed: () async {
                    try {
                      final newuser = await FirebaseAuth.instance
                          .createUserWithEmailAndPassword(
                        email: email ?? 'error',
                        password: password ?? 'error',
                      );
                      await FirebaseFirestore.instance
                          .collection('Users')
                          .add({' uname': username});

                      if (newuser != null) {
                        Navigator.push(
                          context,
                          MaterialPageRoute(builder: (context) => home()),
                        );
                      }
                    } catch (e) {
                      print(e);
                    }
                  }

但我不知道如何從另一個文件訪問它,或者更具體地說,我想在配置文件屏幕上訪問它。

如何從 flutter 中的 firestore 訪問 uname 字段?

雲控制台

您應該在initState中調用文檔並使用setState設置字符串的值

代碼:

class ProfileScreen extends StatefulWidget {
  const ProfileScreen({super.key});

  @override
  State<ProfileScreen> createState() => _ProfileScreenState();
}

class _ProfileScreenState extends State<ProfileScreen> {
  String? name;

  @override
  void initState() {
    FirebaseFirestore.instance
        .collection('Users')
        .doc(FirebaseAuth.instance.currentUser!.uid)
        .get()
        .then((value) {
      print(value.data()?[' uname'];
      setState(() {
        name = value.data()?[' uname'];
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child:
              name != null ? Text(name!) : const CircularProgressIndicator()),
    );
  }
}

我認為更好的方法是將集合(“用戶”)中的文檔 ID 設置為與經過身份驗證的用戶的 uid 相同。 所以獲取詳細信息或在這種情況下,uname 會更容易。

使用與用戶 uid 相同的 docID 創建文檔:

await FirebaseFirestore.instance
    .collection('Users')
    .doc(newUser.uid)
    .add({' uname': username});

獲取詳細信息:

final userData = await FirebaseFirestore.instance
    .collection("Users")
    .doc(FirebaseAuth.instance.currentUser!.uid)
    .get();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM