我想将我的 friend 用户 ID 存储在我的 friend 集合中。
我不知道如何在其他用户集合中存储某人的详细信息。
这是我获取当前用户的代码。
Future<void> _getUserDoc() async {
final FirebaseAuth _auth = FirebaseAuth.instance;
final Firestore _firestore = Firestore.instance;
FirebaseUser user = await _auth.currentUser();
setState(() {
userRef = _firestore.collection('users').document(user.uid);
});
}
数据库结构
USERS
-user1 (current user)
-name: John
-age: 20
--FRIENDS
----user2id
----user3id
-user2
-name: Richie
-age: 20
--FRIENDS
----user3id
这个问题有两部分- 1) 如何将 user2id 和 user3id 存储在 user1 FRIENDS 集合中。 2) 如何检索 user2 数据字段并在小部件中显示。
这是我的小部件代码,我想在其中显示用户 2 的名称。
Padding(
padding:
const EdgeInsets.only(left: 20.0, right: 20.0, top: 10.0),
child: Text(
'20',
style: TextStyle(
fontFamily: 'Montserrat',
fontWeight: FontWeight.bold,
fontSize: 17.0),
),
),
我想在文本小部件中显示来自 firestore 的 user2 年龄,而不是 20。
提前致谢。
最佳答案
我认为存储其他用户 DocumentReference 的最简单方法,如果您将其他用户 DocumentReference
存储在当前用户中,您可以使用 FutureBuilder
红色框内:friends 是其他用户 DocumentReference
的数组
例如你有用户模型
class UserModel {
final int age;
final String name;
final List<DocumentReference> friends;
UserModel(this.age, this.name, this.friends);
// to get from Firestore
UserModel.fromSnapshot(DocumentSnapshot snapshot):
age = snapshot['age'],
name = snapshot['name'],
friends = List.from(snapshot['friends']);
}
我假设您从 firestore 获取当前用户
UserModel currentUser;
FutureBuilder(
future: currentUser.friends.first.get(), // this will take the first friend of current user
// or you can query the list here with where
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Center(child: Text('Connection State none'));
case ConnectionState.active:
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.done:
if (snapshot.hasError)
return Center(child: Text('Error: ${snapshot.error}'));
return Padding(
padding:
const EdgeInsets.only(left: 20.0, right: 20.0, top: 10.0),
child: Text(
snapshot.data['age'],
style: TextStyle(
fontFamily: 'Montserrat',
fontWeight: FontWeight.bold,
fontSize: 17.0),
),
);
}
});
我希望这能解决您的问题。
关于dart - 如何将某人的用户 ID 存储在我的 friend 集合中以及如何使用带有 flutter 的 firestore 检索该用户的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55251725/