Flutter:如何跳过地图迭代中的一个元素?

问题描述

我正在从Firebase中获取数据,并且我不想获取create_uid与uid相同的元素。所以问题是当在地图上运行迭代时,如何跳过某些元素。

  // list from snapshot
  List<ImageProperty> _pictureListFromSnapShot(QuerySnapshot snapshot) {
    return snapshot.documents.map((doc) {
      return  ImageProperty(
              title: doc.data['title'] ?? null,filename: doc.data['filename'] ?? null,token: doc.data['token'] ?? null,filelocation: doc.data['filelocation'] ?? null,url: doc.data['url'] ?? null,created: doc.data['created'] ?? null,creator_uid: doc.data['creator_uid'] ?? null,format: doc.data['format'] ?? null,created_date: doc.data['created_date'].toString() ?? null,timestamp: doc.data['timestamp'] ?? null,tag_label: doc.data['tag_label'] ?? null,user_tag: doc.data['user_tag'] ?? null,rating: doc.data['rating'] ?? 0,score: doc.data['score'] ?? 0,display_count: doc.data['score_display_count'] ?? 0,judges: doc.data['judges'] ?? null,isClicked: false,isShown: false,);
    }).toList();
  }

  // get test stream
  Stream<List<ImageProperty>> get pictureData {
    return pictureCollection.snapshots().map(_pictureListFromSnapShot);
  }

请帮助我。谢谢。我期待着您的回音。

解决方法

 List<ImageProperty> _pictureListFromSnapShot(QuerySnapshot snapshot) {

List<dynamic> filterlist =  snapshot.documents.where((doc){
return doc.data['creator_uid'] !=uid}).toList(); 

return filterlist.map((doc) {
  return  ImageProperty(
          title: doc.data['title'] ?? null,filename: doc.data['filename'] ?? null,token: doc.data['token'] ?? null,filelocation: doc.data['filelocation'] ?? null,url: doc.data['url'] ?? null,created: doc.data['created'] ?? null,creator_uid: doc.data['creator_uid'] ?? null,format: doc.data['format'] ?? null,created_date: doc.data['created_date'].toString() ?? null,timestamp: doc.data['timestamp'] ?? null,tag_label: doc.data['tag_label'] ?? null,user_tag: doc.data['user_tag'] ?? null,rating: doc.data['rating'] ?? 0,score: doc.data['score'] ?? 0,display_count: doc.data['score_display_count'] ?? 0,judges: doc.data['judges'] ?? null,isClicked: false,isShown: false,);
  }).toList();
  }

第二个解决方案

  List<ImageProperty> _pictureListFromSnapShot(QuerySnapshot snapshot) 
{

List<ImageProperty> filterlist =  [] 

snapshot.documents.forEach((doc) {
 if(oc.data['creator_uid'] !=uid){
 filterlist.add(ImageProperty(
          title: doc.data['title'] ?? null,));
     }
   
   });
   return filterlist;
  }
,

举一个简单的例子:

给定一个项目列表(在本例中为 int)和一个可能返回 null 的“处理”函数,我们希望返回一个处理过的项目数组没有空值。

如果我们想使用 map 函数,我们不能跳过这些项目,所以我们必须首先处理这些项目,然后用 where 过滤掉它们,然后强制转换为 not null(为了 null 安全)。

另一种选择是使用 expand 函数,因为如果返回空数组,它将跳过该项目

示例代码:

///Just an example process function
int? process(int val) => val > 0 ? val * 100 : null;

void main() {
  /// Our original array
  final List<int> orig = [1,2,-5,3,-1,-3];

  /// Using map and filter
  final List<int?> map = orig
      .map((e) => process(e)) // <--mapped to results but with null
      .where((e) => e != null) //<--remove nulls
      .cast<int>() //<-- cast to not nullable as there are none
      .toList(); //<-- convert to list

  /// Using expand
  final filtered = orig.expand((val) {
    final int? el = process(val);
    return el == null ? 
      [] : //<-- returning an empty array will skip the item
      [el];
  }).toList();

  print("Origin : $orig");
  print("Transformed with map : $map");
  print("Transformed with expand : $filtered");
}

您还可以扩展迭代器以便于访问:

///Just an example process function
int? process(int val) => val > 0 ? val * 100 : null;

/// Our extension
extension MapNotNull<E> on Iterable<E> {
  Iterable<T> mapNotNull<T>(T? Function(E e) transform) => this.expand((el) {
        final T? v = transform(el);
        return v == null ? [] : [v];
      });
}

void main() {
  /// Our original array
  final List<int> orig = [1,-3];
  /// Will automatically skip null values
  final List<int> filtered = orig.mapNotNull((e)=>process(e)).toList();

  print("Origin : $orig");
  print("Filtered : $filtered");
}