可以使用Flutter将字符串与Firebase实时DB的钥匙值进行比较吗?

发布于 2025-02-10 21:44:28 字数 3017 浏览 0 评论 0 原文

我是Flutter和Firebase的新手,正在尝试显示登录的当前用户的数据。我自己尝试了各种方式,例如将当前用户电子邮件存储在字符串变量上,并将其与他们的电子邮件密钥进行比较,但无法弄清楚如何做。

有没有办法将快照作为仅登录的用户数据的输出?

“数据库”

    import 'package:firebase_database/firebase_database.dart';
import 'package:firebase_database/ui/firebase_animated_list.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:helloworld/tictactoe.dart';
import 'package:helloworld/numbergame.dart';
import 'package:helloworld/profile.dart';

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      // Remove the debug banner
      debugShowCheckedModeBanner: false,
      title: 'Search',
      home: Search(),
    );
  }
}

class Search extends StatefulWidget {
  const Search({Key? key}) : super(key: key);
  static const String id = 'search';
  @override
  _SearchState createState() => _SearchState();
}

class _SearchState extends State<Search> with AutomaticKeepAliveClientMixin {
  final dbRef = FirebaseDatabase.instance.ref().child("insertdata");
  List<Map<dynamic, dynamic>> lists = [];

  final _auth = FirebaseAuth.instance;
  late String? userEmail;
  void getCurrentUserEmail() async {
    final user = await _auth.currentUser;
    userEmail = user!.email;
  }
  void initState() {
    super.initState();
    getCurrentUserEmail();
  }
  @override
  Widget build(BuildContext context) {
    super.build(context);
    //btmnavbar

    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: FutureBuilder<DatabaseEvent>(
          future: dbRef.once(),
          builder: (context, AsyncSnapshot<DatabaseEvent> snapshot) {
            if (snapshot.hasData) {
              lists.clear();
              Map<dynamic, dynamic> values = snapshot.data!.snapshot.value as Map<dynamic, dynamic>;
              values.forEach((key, values) {
                lists.add(values);
              });
              return new ListView.builder(
                  shrinkWrap: true,
                  itemCount: lists.length,
                  itemBuilder: (BuildContext context, int index) {
                    return Card(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text("Name: " + lists[index]["Email"]),
                          Text("Age: " + lists[index]["First Name"]),
                          Text("Type: " + lists[index]["Last Name"]),
                        ],
                      ),
                    );
                  });
            }
            return CircularProgressIndicator();
          }),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}

I am new to flutter and firebase and am trying to display the data of the current user that has logged in. I tried various ways myself like storing the current user email on a String variable and comparing it with they email key, but couldn't figure out how to do it.

Is there a way to get the snapshot as output of only the logged in user data?

Database

    import 'package:firebase_database/firebase_database.dart';
import 'package:firebase_database/ui/firebase_animated_list.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:helloworld/tictactoe.dart';
import 'package:helloworld/numbergame.dart';
import 'package:helloworld/profile.dart';

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      // Remove the debug banner
      debugShowCheckedModeBanner: false,
      title: 'Search',
      home: Search(),
    );
  }
}

class Search extends StatefulWidget {
  const Search({Key? key}) : super(key: key);
  static const String id = 'search';
  @override
  _SearchState createState() => _SearchState();
}

class _SearchState extends State<Search> with AutomaticKeepAliveClientMixin {
  final dbRef = FirebaseDatabase.instance.ref().child("insertdata");
  List<Map<dynamic, dynamic>> lists = [];

  final _auth = FirebaseAuth.instance;
  late String? userEmail;
  void getCurrentUserEmail() async {
    final user = await _auth.currentUser;
    userEmail = user!.email;
  }
  void initState() {
    super.initState();
    getCurrentUserEmail();
  }
  @override
  Widget build(BuildContext context) {
    super.build(context);
    //btmnavbar

    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: FutureBuilder<DatabaseEvent>(
          future: dbRef.once(),
          builder: (context, AsyncSnapshot<DatabaseEvent> snapshot) {
            if (snapshot.hasData) {
              lists.clear();
              Map<dynamic, dynamic> values = snapshot.data!.snapshot.value as Map<dynamic, dynamic>;
              values.forEach((key, values) {
                lists.add(values);
              });
              return new ListView.builder(
                  shrinkWrap: true,
                  itemCount: lists.length,
                  itemBuilder: (BuildContext context, int index) {
                    return Card(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text("Name: " + lists[index]["Email"]),
                          Text("Age: " + lists[index]["First Name"]),
                          Text("Type: " + lists[index]["Last Name"]),
                        ],
                      ),
                    );
                  });
            }
            return CircularProgressIndicator();
          }),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

以为你会在 2025-02-17 21:44:28

如果您有用户的电子邮件地址,则可以使用查询在其电子邮件属性中仅选择具有该值的节点,

future: dbRef.orderByChild("Email").equalTo("[email protected]").once(),

或者如果您有变量 useremail 其中的电子邮件地址:

future: dbRef.orderByChild("Email").equalTo(userEmail).once(),

另请参阅来自实时数据库。

If you have the user's email address, you can use a query to select just the nodes with that value in their Email property with:

future: dbRef.orderByChild("Email").equalTo("[email protected]").once(),

Or if you have a variable userEmail with the email address in it:

future: dbRef.orderByChild("Email").equalTo(userEmail).once(),

Also see the Firebase documentation on ordering and filtering data from the Realtime Database.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文