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

1 dictionary iterator snapshot dart 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);
  }
Run Code Online (Sandbox Code Playgroud)

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

Plo*_*kko 5

让我们用一个简单的例子:

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

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

另一种选择是使用 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, 0, -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");
}
Run Code Online (Sandbox Code Playgroud)

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

///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, 2, -5, 3, 0, -1, -3];
  /// Will automatically skip null values
  final List<int> filtered = orig.mapNotNull((e)=>process(e)).toList();

  print("Origin : $orig");
  print("Filtered : $filtered");
}
Run Code Online (Sandbox Code Playgroud)