Flutter中Firebase实时数据库字符串查询失效问题求助
问题原因
Firebase实时数据库的排序规则是类型优先:数字类型的值会全部排在字符串类型的值前面。你当前用startAt('sam').endAt('1'),这里的'1'是字符串,数据库里的int类型Series值会被解析为数字,排在所有字符串前面,所以能被查询到;但以'sam'开头的字符串类型值在排序序列里处于数字之后,endAt('1')(字符串)的范围不会覆盖到这些字符串,自然查不到。
解决方案
- 修正查询范围:如果要匹配所有以'sam'开头的字符串,应该用
endAt('sam\uf8ff')。\uf8ff是Unicode中一个非常靠后的字符,能匹配所有以'sam'开头的后续字符组合。 - 统一字段类型:建议把
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
相关产品推荐
相关产品推荐

