如何从firebase中获取用户数据进行查询?

问题描述 投票:0回答:1

我尝试从 Firebase 获取数据,其 userEmail 与当前 userEmailId 不同,其 BloodGroup 与按 documentId 排序的当前 userBlood 相同(降序)。但没有得到想要的结果。如何解决这个问题

我尝试了以下代码,但没有得到想要的结果(未找到捐赠请求)。 打印输出也为空。

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  final controller = Get.put(UserController());
  bool donationRequestsLoading = true;
  Map<String, dynamic> donationMap = {};

  Future<void> fetchDonationRequests() async {
    try {
      final userEmailID = controller.user.value.email;
      final userBlood = controller.user.value.bloodGroup;
      print('blood group: $userBlood');

      QuerySnapshot querySnapshot = await FirebaseFirestore.instance
          .collection("Requests")
          .where("status", isEqualTo: "Pending")
          .where("bloodGroup", isEqualTo: userBlood)
          .where("userEmail", isEqualTo: userEmailID)
          .orderBy(FieldPath.documentId, descending: true)
          .get();

      // Process data
      if (querySnapshot.docs.isNotEmpty) {
        DocumentSnapshot documentSnapshot = querySnapshot.docs.first;
        donationMap = documentSnapshot.data() as Map<String, dynamic>;
      } else {
        donationMap = {}; // No data available
      }
    } catch (e) {
      print("Error fetching donation requests: $e");
    } finally {
      setState(() {
        donationRequestsLoading = false;
      });
    }
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      fetchDonationRequests();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
        child: Column(
          children: [
            const EPrimaryHeaderContainer(
              child: Column(
                children: [
                  EHomeAppBar(),
                  SizedBox(height: ESizes.spaceBtwInputFields),
                  BloodGroupandNextDonation(),
                  SizedBox(height: ESizes.spaceBtwSections),
                ],
              ),
            ),
            const RequestToBloodBank(),
            const SizedBox(height: 28),

            // Post blood request, donate blood, blood banks
            const Padding(
              padding: EdgeInsets.symmetric(horizontal: ESizes.defaultSpace),
              child: Column(
                children: [
                  Row(
                    children: [
                      PostBloodRequest(),
                      SizedBox(width: 12),
                      BloodBanks(),
                      SizedBox(width: 12),
                      DonateBlood(),
                    ],
                  ),
                  SizedBox(height: ESizes.spaceBtwInputFields),
                ],
              ),
            ),

            // Donation Requests Section
            ESectionHeading(
              title: 'Donation Requests',
              showActionButton: true,
              onPressed: () {
                Get.to(() => const DonationRequestsList());
              },
            ),
            const SizedBox(height: 1),

            donationRequestsLoading
                ? const Padding(
              padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0),
              child: EShimmerEffect(
                width: double.infinity,
                height: 110,
                radius: 16,
              ),
            )
                : donationMap.isEmpty
                ? const Center(
              child: Text(
                "No donation requests available.",
                style: TextStyle(fontSize: 16, color: Colors.grey),
              ),
            )
                : DonationRequests(donationMap: donationMap),
            const SizedBox(height: 10),
          ],
        ),
      ),
    );
  }
}
flutter firebase controller
1个回答
0
投票

Firestore 不允许直接使用 isNotEqualToorderBy 来处理排序,您可能需要以不同的方式构建数据或在获取结果后对结果进行排序

您可以使用更新后的代码,如下所示

  // Fetch documents where userEmail is not the current user's email
  QuerySnapshot querySnapshot = await FirebaseFirestore.instance
      .collection("Requests")
      .where("status", isEqualTo: "Pending")
      .where("bloodGroup", isEqualTo: userBlood)
      .where("userEmail", isNotEqualTo: userEmailID) // Exclude current user
      .get();

  // Process data
  donationRequests = querySnapshot.docs.map((doc) {
    return doc.data() as Map<String, dynamic>;
  }).toList();

  print("Fetched ${donationRequests.length} donation requests");
} catch (e) {
  print("Error fetching donation requests: $e");
} finally {
  setState(() {
    donationRequestsLoading = false;
  });
}

不是只处理第一个文档,所有匹配的文档都存储在一个列表中,检查下面的代码

        // Post blood request, donate blood, blood banks
        const Padding(
          padding: EdgeInsets.symmetric(horizontal: ESizes.defaultSpace),
          child: Column(
            children: [
              Row(
                children: [
                  PostBloodRequest(),
                  SizedBox(width: 12),
                  BloodBanks(),
                  SizedBox(width: 12),
                  DonateBlood(),
                ],
              ),
              SizedBox(height: ESizes.spaceBtwInputFields),
            ],
          ),
        ),

        // Donation Requests Section
        ESectionHeading(
          title: 'Donation Requests',
          showActionButton: true,
          onPressed: () {
            Get.to(() => const DonationRequestsList());
          },
        ),
        const SizedBox(height: 1),

        donationRequestsLoading
            ? const Padding(
                padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0),
                child: EShimmerEffect(
                  width: double.infinity,
                  height: 110,
                  radius: 16,
                ),
              )
            : donationRequests.isEmpty
                ? const Center(
                    child: Text(
                      "No donation requests available.",
                      style: TextStyle(fontSize: 16, color: Colors.grey),
                    ),
                  )
                : ListView.builder(
                    shrinkWrap: true,
                    physics: const NeverScrollableScrollPhysics(),
                    itemCount: donationRequests.length,
                    itemBuilder: (context, index) {
                      final request = donationRequests[index];
                      return DonationRequests(donationMap: request);
                    },
                  ),
        const SizedBox(height: 10),
      ],
    ),
  ),
);

如果代码有效,请不要忘记点赞:)

© www.soinside.com 2019 - 2024. All rights reserved.