Android 如何检索单个文档数据并在应用程序中显示?
在这里,我试图打印用户的用户名,它会产生以下错误。 我创建了一个函数userData(),代码是Android 如何检索单个文档数据并在应用程序中显示?,android,firebase,flutter,google-cloud-firestore,Android,Firebase,Flutter,Google Cloud Firestore,在这里,我试图打印用户的用户名,它会产生以下错误。 我创建了一个函数userData(),代码是 userData() async { var userData = await _db.collection('users').document(_uuid).get(); return userData; } 在这里,我将使用uid获取特定用户的数据并返回它 我用来打印数据的代码如下 return FutureBuilder( future: authServi
userData() async
{
var userData = await _db.collection('users').document(_uuid).get();
return userData;
}
在这里,我将使用uid获取特定用户的数据并返回它
我用来打印数据的代码如下
return FutureBuilder(
future: authService.userData(),
builder: (_,snapshots){
if(snapshots.connectionState == ConnectionState.waiting)
{
return Center(child: Text('Loading...'),);
}
else{
print("Snapshots: "+snapshots.toString());
return ListView.builder(itemCount: 1, itemBuilder: (_,index){
return ListTile(
title: Text(snapshots.data["username"].toString()),
);
});
}
}
);
firestore的结构是
集合('user')->文档(uid)->1.username 2.email
此错误的原因是什么以及如何解决?对于Firestore,我建议使用Stream Builder而不是未来的Builder
return StreamBuilder(
stream: Firestore.instance
.collection('user')
.document(uid)
.snapshots(),
builder: (_,snapshot){
if(!snapshot.hasData)
{
return Center(child: Text('Loading...'),);
}
else{
return ListView.builder(itemCount: 1, itemBuilder: (_,index){
return ListTile(
title: Text(snapshots.data["username"].toString()),
);
});
}
}
);
对于Firestore,我建议使用流生成器,而不是未来的生成器
return StreamBuilder(
stream: Firestore.instance
.collection('user')
.document(uid)
.snapshots(),
builder: (_,snapshot){
if(!snapshot.hasData)
{
return Center(child: Text('Loading...'),);
}
else{
return ListView.builder(itemCount: 1, itemBuilder: (_,index){
return ListTile(
title: Text(snapshots.data["username"].toString()),
);
});
}
}
);
错误消息告诉您,
snapshots.data
为空,因此您无法使用[]
运算符对其进行索引
在使用之前,您应该在访问字段数据之前检查它是否正确。如果文档不存在,快照的属性将为null。错误消息告诉您,
快照。数据
为null,因此您无法使用[]
操作符对其进行索引
在使用之前,您应该在访问字段数据之前检查它是否正确。如果文档不存在,快照的属性将为null。出于测试目的,我使用了firestore中存在的文档ID。因为它返回null。原因是什么?SDK告诉您文档不存在。我无法验证这一点,因为我看不到您正在使用的数据。是的,现在我已将firestore数据更新为Images,我们仍然看不到您传递的
\uuid
值是否正确。如果传递文档ID以外的任何内容,快照将不包含任何数据。我刚刚在firestore中分配了相同的_uuid。通过复制、粘贴并为测试目的分配值,我使用了firestore中存在的文档ID。因为它返回null。原因是什么?SDK告诉您文档不存在。我无法验证这一点,因为我看不到您正在使用的数据。是的,现在我已将firestore数据更新为Images,我们仍然看不到您传递的\uuid
值是否正确。如果传递文档ID以外的任何内容,快照将不包含任何数据。我刚刚在firestore中分配了相同的_uuid。只需复制、粘贴并为_uuid赋值