【问题标题】:FirestoreFirebase Query to match a specific data within a specific collectionFirestore Firebase 查询以匹配特定集合中的特定数据
【发布时间】:2022-11-11 21:24:43
【问题描述】:

我已经在用户集合中存储了数据(来自 Auth 表的每个用户的 UID)。我需要从用户那里获取数据并将其与currentSignedIn 用户的 UID 匹配。如果当前登录用户的 UID 与集合中的 UID 匹配,则页面可能会返回或导航到第 1 页,否则导航到第 2 页。

目前,仅显示用户集合中的 UID 和 currentSignedIn 用户的 UID 即可查看数据。现在我需要一种方法来匹配数据并使用 if-else 语句。

代码:

@override
  _ProfilePageState createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> {
  Future _getDatafromDatabase() async{
  await FirebaseFirestore.instance.collection('users')
      .doc().get().then((snapshot) async
  {
    if(snapshot.exists)
      {
        setState(() {
          useruid = snapshot.data()!["useruid"];
        });
      }
  });
}
List<Users> uidofusers = [];
@override
void initState(){
    fetchRecords();
    FirebaseFirestore.instance.collection('users').snapshots().listen((records) {
    mapRecords(records);
    });
    super.initState();
}
fetchRecords() async {
var records = await FirebaseFirestore.instance.collection('users').get();
mapRecords(records);
}
mapRecords(QuerySnapshot<Map<String, dynamic>>records) {
var _list = records.docs
    .map((item)=>Users(
    useruid: item['useruid'],
)
).toList();
setState(() {
  uidofusers = _list;
});
}


  @override
  Widget build(BuildContext context)
  {

    return Scaffold(
        appBar: AppBar(
            centerTitle: true,
            title: const Text("Update Profile", style: TextStyle(fontSize: 30.0),),
            backgroundColor: Colors.blue,
            actions: [
              IconButton(
                icon: const Icon(Icons.logout),
                onPressed: () => FirebaseAuth.instance.signOut(),
              ),

            ]
        ),
        body: ListView.builder(
          itemCount: uidofusers.length,
          itemBuilder: (context, index){
            return ListTile(
              title: Text(uidofusers[index].useruid),
              subtitle: Text(uid!),

            );
          },
        ),

【问题讨论】:

    标签: flutter firebase google-cloud-firestore


    【解决方案1】:

    如果您使用用户的 UID 作为其文档 ID 存储用户的文档(推荐),您可以通过以下方式获取它:

    FirebaseFirestore.instance.collection('users')
      .doc(uidOfTheUser)
      .get()
    

    如果你将用户的文档存储在一个随机生成的文档ID下,带有一个带有UID的字段useruid,你可以use a query获取文档:

    FirebaseFirestore.instance.collection('users')
      .where("useruid", isEqualTo: uidOfTheUser)
      .get()
    

    在后一种情况下,可能有 multiple documents 匹配条件,因此您会返回需要循环的 QuerySnapshot

    【讨论】:

      猜你喜欢
      • 2018-06-19
      • 1970-01-01
      • 2023-02-07
      • 2021-11-08
      • 1970-01-01
      • 1970-01-01
      • 2018-07-31
      • 2021-01-03
      • 2018-12-09
      相关资源
      最近更新 更多