flutter - 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);
});
}
解决方案
像这样修改你的方法:
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 将返回一个标题,您将在屏幕上看到它。很可能不是你想要的。我会在你的应用程序开始时加载这些东西,将文本保存在你的脚手架可以访问它的地方。
此外,每次您的脚手架重建时,您都会进行数据库调用并再次重新加载标题。因为我假设标题或多或少是静态的,所以这也是不行的。但我希望这可以帮助你开始。
推荐阅读
- php - Laravel 已弃用错误:idn_to_ascii(): INTL_IDNA_VARIANT_2003 已弃用
- openssl - 将私钥转换为 PKCS#8
- react-native - 当父组件使用 withNavigation 时,navigation.goBack() 是否在子组件中工作?
- android - 扩展的 RecycleView 滞后
- c++ - 如何从代码中删除类并仍然使其工作?
- c# - Umbraco ADFS 集成 (OpenIdConnect) GroupSid 未设置?
- admob - 对 Sniffer/Modder/Hacker 隐藏 Admob APP ID
- ruby-on-rails - 如何使redirect_to 以远程形式工作?
- reactjs - 在我的情况下,如何将 componentDidMount 重新制作为 useEffect?
- android - Room Entity 的数据存储正确,但检索为 null