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

Flutter中如何对JSON数据进行筛选?附Firestore筛选示例

为JSON数据实现与Firestore一致的筛选逻辑

你只需要在JSON数据解析完成后,给生成的Station50K列表(或原始JSON数据)加上和Firestore完全一致的筛选条件即可。以下是两种实现方式:

方式一:先转模型再筛选(可读性优先)

这种方式先把JSON数据转为Station50K对象,再直接通过模型字段进行筛选,代码更直观:

Future<List<Station50K>> _getStationsRemoteJson() async {
  const url = 'JSON URL'; 

  final response = await http.get(Uri.parse(url));
  final body = json.decode(response.body);
  final stationsJson = body['data'];

  // 将JSON数组转为Station50K对象列表
  final stations = stationsJson.map<Station50K>(Station50K.fromJson2).toList();

  // 应用与Firestore一致的筛选规则
  final filteredStations = stations.where((station) {
    // 检查当前电台ID是否在收藏列表中
    final isFavorite = _favorites.contains(station.id.toString());
    if (!isFavorite) return false;

    // 统一处理搜索文本,避免重复转小写
    final lowerSearchText = _searchText.toLowerCase();

    // 检查标题是否匹配
    final titleMatches = station.title.toString().toLowerCase().contains(lowerSearchText);
    if (titleMatches) return true;

    // 检查城市是否匹配
    final cityMatches = station.city.toString().toLowerCase().contains(lowerSearchText);
    if (cityMatches) return true;

    // 检查流派列表中是否有任意项匹配
    final genreMatches = station.genre.any((genre) => 
      genre.toString().toLowerCase().contains(lowerSearchText)
    );
    return genreMatches;
  }).toList();

  return filteredStations;
}

方式二:先筛选JSON再转模型(性能优先)

如果JSON数据量很大,先筛选原始JSON数据再转为模型,可以减少不必要的对象实例化,提升性能:

Future<List<Station50K>> _getStationsRemoteJson() async {
  const url = 'JSON URL'; 

  final response = await http.get(Uri.parse(url));
  final body = json.decode(response.body);
  final stationsJson = body['data'] as List;

  // 先对原始JSON数据进行筛选
  final filteredJson = stationsJson.where((jsonItem) {
    // 检查ID是否在收藏列表
    final isFavorite = _favorites.contains(jsonItem['id'].toString());
    if (!isFavorite) return false;

    final lowerSearchText = _searchText.toLowerCase();
    
    // 检查标题、城市、流派的匹配逻辑
    final titleMatches = jsonItem['title'].toString().toLowerCase().contains(lowerSearchText);
    final cityMatches = jsonItem['city'].toString().toLowerCase().contains(lowerSearchText);
    final genreMatches = List.from(jsonItem['genre']).any((genre) => 
      genre.toString().toLowerCase().contains(lowerSearchText)
    );

    return titleMatches || cityMatches || genreMatches;
  }).toList();

  // 将筛选后的JSON转为Station50K列表
  return filteredJson.map<Station50K>(Station50K.fromJson2).toList();
}

关键说明

两种方式的筛选逻辑和你在Firestore中使用的完全一致:

  1. 先判断电台ID是否存在于_favorites收藏列表
  2. 再依次检查标题、城市是否包含搜索文本(不区分大小写)
  3. 最后检查流派列表中是否有任意一项包含搜索文本(不区分大小写)

内容的提问来源于stack exchange,提问作者Gökhan E.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 10:48:19