You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firestore查询匹配当前用户UID实现页面跳转需求

实现方案

1. 核心逻辑说明

我们需要先获取当前登录用户的UID,再检查该UID是否存在于Firestore的users集合中,根据匹配结果跳转至对应页面。

2. 具体代码实现

修改后的完整代码

@override
_ProfilePageState createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> {
  List<Users> uidofusers = [];
  bool _hasNavigated = false; // 标记是否已完成跳转,避免重复执行

  @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) {
    String? currentUserUid = FirebaseAuth.instance.currentUser?.uid;

    // 执行匹配判断与页面跳转
    if (!_hasNavigated && currentUserUid != null && uidofusers.isNotEmpty) {
      _hasNavigated = true;
      bool isMatched = uidofusers.any((user) => user.useruid == currentUserUid);
      
      // 确保页面挂载后再执行跳转
      WidgetsBinding.instance.addPostFrameCallback((_) {
        // 替换为你的Page1和Page2组件
        Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => isMatched ? Page1() : Page2()));
      });
    }

    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(currentUserUid ?? "未登录"),
            );
          },
        ),
    );
  }
}

关键改动说明

  • 添加_hasNavigated状态变量,防止页面重复跳转
  • 在build方法中完成匹配判断:使用any方法检查当前用户UID是否存在于集合列表中
  • 使用WidgetsBinding.instance.addPostFrameCallback确保页面完全挂载后再执行跳转操作
  • 替换subtitle的文本为当前用户UID,明确展示对比内容

注意事项

  • 确保Page1和Page2是你已定义的页面组件
  • 使用pushReplacement会替换当前页面栈,用户无法返回当前页,若需保留返回路径可替换为push
  • 可补充用户未登录时的处理逻辑(如跳转登录页)

内容的提问来源于stack exchange,提问作者Muhammad Zunair Shahzad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 04:05:40