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

Flutter中Firebase实时数据库字符串查询失效问题求助

问题原因

Firebase实时数据库的排序规则是类型优先:数字类型的值会全部排在字符串类型的值前面。你当前用startAt('sam').endAt('1'),这里的'1'是字符串,数据库里的int类型Series值会被解析为数字,排在所有字符串前面,所以能被查询到;但以'sam'开头的字符串类型值在排序序列里处于数字之后,endAt('1')(字符串)的范围不会覆盖到这些字符串,自然查不到。

解决方案
  1. 修正查询范围:如果要匹配所有以'sam'开头的字符串,应该用endAt('sam\uf8ff')。\uf8ff是Unicode中一个非常靠后的字符,能匹配所有以'sam'开头的后续字符组合。
  2. 统一字段类型:建议把Series字段的类型统一为字符串,避免数字和字符串混合存储,否则后续查询还会出现类似排序问题。
修正后的代码
DatabaseReference starCountRef =
      FirebaseDatabase.instance.ref('/Shop/qw1234/Inventory/');

bool data = false;

Expanded(
  child: FirebaseAnimatedList(
      query: starCountRef
          .orderByChild('Series')
          .startAt('sam')
          .endAt('sam\uf8ff'), // 修正endAt参数
      itemBuilder: (context, snapshot, animation, index) {
        return ListTile(
          onTap: (() {
            print(index);
          }),
          title: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                children: [
                  Text('Price: Rs '),
                  Text(
                      snapshot.child('Price').value.toString()),
                ],
              ),
            ],
          ),
          subtitle: Padding(
            padding: const EdgeInsets.only(top: 10, bottom: 10),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Text(
                      'Model: ',
                      style: TextStyle(
                          fontWeight: FontWeight.bold),
                    ),
                    Text(snapshot
                        .child('Series')
                        .value
                        .toString()),
                  ],
                ),

              ],
            ),
          ),
        );
      }),
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 07:17:11