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

Flutter查询Firestore失败交易日志时出现failed-precondition错误求助

解决Firestore查询返回failed-precondition错误问题

在Flutter项目中查询失败交易日志时,触发错误:flutter: Failed with error code: failed-precondition

数据库结构如下:
Firestore数据库结构

查询代码

@override
Future<List<InvoiceModel>> fetchFailedTransactionLog() async {
  final snapshot = await db.collection(firestoreUsers)
  .doc(currentUser!.uid)
  .collection(firestoreTransacitonLog)
  .where('isSuccess', isEqualTo: false)
  .orderBy('created', descending: true)
  .get();
  final data = snapshot.docs.map((e) => InvoiceModel.fromFirestore(e)).toList();
  print('DATA =============> ${data}');
  return data;
}

Firestore安全规则

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth != null;
    }
  }
}

InvoiceModel模型类

class InvoiceModel extends Equatable{
  final String id;
  final String invoiceNumber;
  final String paymentNumber;
  final String paymentMethod;
  final String name;
  final String? email;
  int? phoneNumber;
  final String? address;
  final DateTime created;
  final DateTime startDate;
  final DateTime expiryDate;
  final String? description;
  int nominal;
  int quantity;
  int total;
  bool? isSuccess;

  InvoiceModel({
    required this.id,
    required this.invoiceNumber,
    required this.paymentNumber,
    required this.paymentMethod,
    required this.name,
    this.email = "",
    this.phoneNumber,
    this.address = "",
    required this.created,
    required this.startDate,
    required this.expiryDate,
    this.description = "",
    required this.nominal,
    this.quantity = 1,
    required this.total,
    this.isSuccess
  });
}

已尝试操作

把查询条件从isEqualTo: false改成isNotEqualTo: true,错误依旧。同时纠结要不要把isSuccess字段从布尔类型改成字符串类型。


问题排查与解决步骤

1. 必须创建复合索引

Firestore同时使用where和orderBy查询时,必须手动创建对应的复合索引,否则会返回failed-precondition错误。创建步骤:

  • 打开Firebase控制台,进入Firestore数据库页面
  • 切换到「索引」标签,点击「添加索引」
  • 集合路径填users/{userId}/transactionLog(根据你实际的集合名称调整)
  • 字段选择isSuccess(升序降序均可)和created(选降序,与查询排序一致)
  • 勾选启用,等待几分钟索引创建完成后再测试查询

2. 校验字段类型一致性

去Firebase控制台查看transactionLog集合下的文档,确认isSuccess字段的实际类型是布尔值(true/false),而非字符串("true"/"false")。如果类型不匹配,要么批量更新现有文档的字段类型,要么调整查询条件的类型与数据库一致。

3. 确认用户认证状态

虽然安全规则要求登录,但仍需确保查询时currentUser不为null。可以在调用查询方法前添加判断:

if (currentUser == null) {
  throw Exception("用户未登录");
}

同时检查用户认证流程是否正确,currentUser是否已正确初始化。

4. 检查拼写错误

注意代码中的集合名firestoreTransacitonLog是否存在拼写错误(疑似多了一个字母,正确应为transactionLog?),集合名拼写错误也会导致查询失败。


内容的提问来源于stack exchange,提问作者Koya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 00:47:48