Flutter多搜索功能报错:null不是String子类型问题排查
解决Multisearch兼容字符串与数字搜索的类型错误问题
错误原因
"null isn't subtype of string" 本质是搜索逻辑里未处理空值,或者字段类型不统一导致的:比如JSON里的数字字段(int类型)直接和字符串输入做匹配,或者某个字段为null时被强制当作String处理。
解决方案
1. 统一搜索输入的处理
先把用户输入统一转为字符串,同时处理空输入的情况,避免后续调用字符串方法报错:
final searchQuery = input?.toString().toLowerCase().trim() ?? '';
2. 兼容多类型字段的匹配逻辑
把所有需要搜索的字段(不管是String还是int类型)统一转为字符串,并兜底空值,再做包含匹配:
bool matches(Item item, String query) { // 字符串字段转小写,空值兜底为'' final name = item.name?.toLowerCase() ?? ''; final desc = item.description?.toLowerCase() ?? ''; // 数字字段直接转字符串,空值兜底为'' final itemId = item.id?.toString() ?? ''; return name.contains(query) || desc.contains(query) || itemId.contains(query); }
3. 完整搜索示例
假设你的数据模型和搜索函数如下,这样就能同时兼容字符串和数字搜索:
// 数据模型 class Item { final String? name; final int? id; final String? description; Item({this.name, this.id, this.description}); factory Item.fromJson(Map<String, dynamic> json) => Item( name: json['name'], id: json['id'], description: json['description'], ); } // 搜索函数 List<Item> searchLocalItems(List<Item> allItems, String? userInput) { final query = userInput?.toString().toLowerCase().trim() ?? ''; if (query.isEmpty) return allItems; return allItems.where((item) { final name = item.name?.toLowerCase() ?? ''; final itemId = item.id?.toString() ?? ''; final desc = item.description?.toLowerCase() ?? ''; return name.contains(query) || itemId.contains(query) || desc.contains(query); }).toList(); }
4. 第三方Multisearch库配置注意事项
如果你用的是第三方Multisearch库(比如multisearch_flutter),构建索引时要把数字字段按字符串类型配置,确保索引能兼容数字搜索:
final searchIndex = Index( fields: [ Field(name: 'name', type: FieldType.string), Field(name: 'id', type: FieldType.string), // 数字字段按字符串索引 Field(name: 'description', type: FieldType.string), ], );
内容的提问来源于stack exchange,提问作者Danial
相关产品推荐
相关产品推荐

