首页 > 解决方案 > Flutter:从 Firestore 获取特定数据并以文本形式输出

问题描述

我是颤振/飞镖的新手。我需要在 firestore 中获取特定数据并将其输出为文本,例如:Collection - Document(currentUID) - Field(Name)。我需要获取该数据,即“名称”并将其设置为我的 AppBar 名称。

这是我到目前为止所做的代码。非常需要帮助,谢谢。

我已设法在终端中打印名称,但无法将其设置为我的 AppBar 名称。

 _loadcurrentName() async{
    await Firestore.instance.collection('USER').document(currentUser.uid).get().then((DocumentSnapshot ds) async {
      var name = ds['Name'];
      print(name);
    });
  }

标签: flutterdart

解决方案


像这样修改你的方法:

 Future<String> _getAppBarNameWidget() async{
    await Firestore.instance.collection('USER').document(currentUser.uid).get().then((DocumentSnapshot ds) async {
      var name = ds['Name'];
      return name;
    });
  }

在你的脚手架代码的某个地方,这样做:

return Scaffold(
        appBar: AppBar(
          title: FutureBuilder(
             future: _getAppBarNameWidget(),
             builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
               return Text(snapshot.data);
             }),
          actions: <Widget>[AppBarNotificationAction()],
        )
       );

但是由于您的方法是异步的,您肯定会首先出现没有标题的 Scaffold,然后在几毫秒后,FutureBuilder 将返回一个标题,您将在屏幕上看到它。很可能不是你想要的。我会在你的应用程序开始时加载这些东西,将文本保存在你的脚手架可以访问它的地方。

此外,每次您的脚手架重建时,您都会进行数据库调用并再次重新加载标题。因为我假设标题或多或少是静态的,所以这也是不行的。但我希望这可以帮助你开始。


推荐阅读