关于flutter:Dart-集合操作插件-DartX

9次阅读

共计 7489 个字符,预计需要花费 19 分钟才能阅读完成。

本次图片是向 kallehallden 致敬,酷爱编程,放弃一颗好奇的心

老铁记得 转发,猫哥会出现更多 Flutter 好文~~~~

微信 flutter 研修群 ducafecat

猫哥说

最近没工夫录视频,始终在做我的项目和技术钻研,就翻译和写写文章和大家分享。

对于这篇文章,我只想说所有让咱们少写代码,让代码简洁的形式都是好货色!

兴许这个组件 dartx 在某些人眼里不够成熟,然而这代表了一种思路,你应该去借鉴。

原文

https://medium.com/flutter-co…

参考

  • https://docs.microsoft.com/en…
  • https://pub.dev/packages/dartx

注释

Darts Iterable 和 List 提供了一组根本的办法来批改和查问汇合。然而,来自 c # 背景,它有一个不凡的 LINQ-to-Objects 库,我感觉我日常应用的一部分性能缺失了。当然,任何工作都能够只应用 dart.core 办法来解决,但有时须要多行解决方案,而且代码不是那么显著,须要破费精力去了解。咱们都晓得,开发人员破费大量工夫浏览代码,使代码简洁明了是至关重要的。

Dartx 包容许开发人员在汇合 (和其余 Dart 类型) 上应用优雅且可读的单行操作。

https://pub.dev/packages/dartx

上面咱们将比拟这些工作是如何解决的:

  • first / last collection item or null / default value / by condition;
  • map / filter / iterate collection items depending on their index;
  • converting a collection to a map;
  • sorting collections;
  • collecting unique items;
  • min / max / average by items property;
  • filtering out null items;

装置 dartx pubspec.yaml

dependencies:
  dartx: ^0.7.1
import 'package:dartx/dartx.dart';

First / last collection item…

… or null

为了失去第一个和最初一个收集我的项目的简略省道,你能够这样写:

final first = list.first;
final last = list.last;

如果 list 为空,则抛出 statereerror,或者显式返回 null:

final firstOrNull = list.isNotEmpty ? list.first : null;
final lastOrNull = list.isNotEmpty ? list.last : null;

应用 dartx 能够:

final firstOrNull = list.firstOrNull;
final lastOrNull = list.lastOrNull;

相似地:

final elementAtOrNull = list.elementAtOrNull(index);

如果索引超出列表的界线,则返回 null。

… or default value

鉴于你当初记住这一点。第一和。当 list 为空时,last getter 会抛出谬误,以获取第一个和最初一个汇合项或默认值,在简略的 Dart 中,你会写:

final firstOrDefault = (list.isNotEmpty ? list.first : null) ?? defaultValue;

final lastOrDefault = (list.isNotEmpty ? list.last : null) ?? defaultValue;

应用 dartx 能够:

final firstOrDefault = list.firstOrDefault(defaultValue);

final lastOrDefault = list.lastOrElse(defaultValue);

相似于 elementAtOrNull:

final elementAtOrDefault = list.elementAtOrDefault(index, defaultValue);

如果索引超出列表的边界,则返回 defaultValue。

… by condition

要获取第一个和最初一个合乎某些条件或 null 的汇合项,一个一般的 Dart 实现应该是:

final firstWhere = list.firstWhere((x) => x.matches(condition));

final lastWhere = list.lastWhere((x) => x.matches(condition));

除非提供 orElse,否则它将为空列表抛出 StateError:

final firstWhereOrNull = list.firstWhere((x) => x.matches(condition), orElse: () => null);

final lastWhereOrNull = list.lastWhere((x) => x.matches(condition), orElse: () => null);

应用 dartx 能够:

final firstWhereOrNull = list.firstOrNullWhere((x) => x.matches(condition));

final lastWhereOrNull = list.lastOrNullWhere((x) => x.matches(condition));

… collection items depending on their index

Map…

当您须要取得一个新的汇合,其中每个我的项目以某种形式依赖于其索引时,这种状况并不常见。例如,每个新项都是来自原始汇合的项及其索引的字符串示意模式。

如果你喜爱我的一句俏皮话,简略地说就是:

final newList = list.asMap()
  .map((index, x) => MapEntry(index, '$index $x'))
  .values
  .toList();

应用 dartx 能够:

final newList = list.mapIndexed((index, x) => '$index $x').toList();

我利用.toList ()是因为这个和大多数其余扩大办法返回 lazy Iterable。

Filter…

对于另一个示例,假如只须要收集奇数索引项。应用简略省道,能够这样实现:

final oddItems = [];
for (var i = 0; i < list.length; i++) {if (i.isOdd) {oddItems.add(list[i]);
  }
}

或者用一行代码:

final oddItems = list.asMap()
  .entries
  .where((entry) => entry.key.isOdd)
  .map((entry) => entry.value)
  .toList();

应用 dartx 能够:

final oddItems = list.whereIndexed((x, index) => index.isOdd).toList();

// or

final oddItems = list.whereNotIndexed((x, index) => index.isEven).toList();

Iterate…

如何记录汇合内容并指定我的项目索引?

In plain Dart:

for (var i = 0; i < list.length; i++) {print('$i: ${list[i]}');
}

应用 dartx 能够:

list.forEachIndexed((element, index) => print('$index: $element'));

Converting a collection to a map

例如,须要将不同 Person 对象的列表转换为 Map < String,Person >,其中键是 Person.id,值是残缺 Person 实例。

final peopleMap = people.asMap().map((index, person) => MapEntry(person.id, person));

应用 dartx 能够:

final peopleMap = people.associate((person) => MapEntry(person.id, person));

// or

final peopleMap = people.associateBy((person) => person.id);

要失去一个 Map,其中键是 DateTime,值是列出那天出世的人的名单 < person >,在简略的 Dart 中,你能够写:

final peopleMapByBirthDate = people.fold<Map<DateTime, List<Person>>>(<DateTime, List<Person>>{},
  (map, person) {if (!map.containsKey(person.birthDate)) {map[person.birthDate] = <Person>[];}
    map[person.birthDate].add(person);
    return map;
  },
);

应用 dartx 能够:

final peopleMapByBirthDate = people.groupBy((person) => person.birthDate);

Sorting collections

你会怎么用一般的 dart 来分类一个收集? 你必须记住这一点

list.sort();

批改源汇合,要失去一个新实例,你必须写:

final orderedList = [...list].sort();

Dartx 提供了一个扩大来取得一个新的 List 实例:

final orderedList = list.sorted();

// and

final orderedDescendingList = list.sortedDescending();

如何基于某些属性对收集项进行排序?

Plain Dart:

final orderedPeople = [...people]
  ..sort((person1, person2) => person1.birthDate.compareTo(person2.birthDate));

应用 dartx 能够:

final orderedPeople = people.sortedBy((person) => person.birthDate);

// and

final orderedDescendingPeople = people.sortedByDescending((person) => person.birthDate);

更进一步,你能够通过多个属性对汇合项进行排序:

final orderedPeopleByAgeAndName = people
  .sortedBy((person) => person.birthDate)
  .thenBy((person) => person.name);

// and

final orderedDescendingPeopleByAgeAndName = people
  .sortedByDescending((person) => person.birthDate)
  .thenByDescending((person) => person.name);

Collecting unique items

要取得不同的汇合项,能够应用以下简略的 Dart 实现:

final unique = list.toSet().toList();

这并不保障放弃我的项目程序或提出一个多行的解决方案

应用 dartx 能够:

final unique = list.distinct().toList();

// and

final uniqueFirstNames = people.distinctBy((person) => person.firstName).toList();

Min / max / average by item property

例如,要查找一个 min/max 汇合项,咱们能够对其进行排序,并获取 first/last 项:

final min = ([...list]..sort()).first;

final max = ([...list]..sort()).last;

同样的办法也实用于按项属性进行排序:

final minAge = (people.map((person) => person.age).toList()..sort()).first;

final maxAge = (people.map((person) => person.age).toList()..sort()).last;

或:

final youngestPerson =
  ([...people]..sort((person1, person2) => person1.age.compareTo(person2.age))).first;

final oldestPerson =
  ([...people]..sort((person1, person2) => person1.age.compareTo(person2.age))).last;

应用 dartx 能够:

final youngestPerson = people.minBy((person) => person.age);

final oldestPerson = people.maxBy((person) => person.age);

对于空集合,它将返回 null。

如果收集我的项目实现了 Comparable,则能够利用不带选择器的办法:

final min = list.min();

final max = list.max();

你也能够很容易地失去平均值:

final average = list.average();

// and

final averageAge = people.averageBy((person) => person.age);

以及 num 汇合或 num 项属性的总和:

final sum = list.sum();

// and

final totalChildrenCount = people.sumBy((person) => person.childrenCount);

Filtering out null items

With plain Dart:

final nonNullItems = list.where((x) => x != null).toList();

应用 dartx 能够:

final nonNullItems = list.whereNotNull().toList();

More useful extensions

在 dartx 中还有其余有用的扩大。这里咱们不会深刻探讨更多细节,然而我心愿命名和代码是不言自明的。

joinToString

final report = people.joinToString(
  separator: '\n',
  transform: (person) => '${person.firstName}_${person.lastName}',
  prefix: '<<️',
  postfix: '>>',
);

all (every) / none

final allAreAdults = people.all((person) => person.age >= 18);

final allAreAdults = people.none((person) => person.age < 18);

first / second / third / fourth collection items

final first = list.first;
final second = list.second;
final third = list.third;
final fourth = list.fourth;

takeFirst / takeLast

final youngestPeople = people.sortedBy((person) => person.age).takeFirst(5);

final oldestPeople = people.sortedBy((person) => person.age).takeLast(5);

firstWhile / lastWhile

final orderedPeopleUnder50 = people
  .sortedBy((person) => person.age)
  .firstWhile((person) => person.age < 50)
  .toList();

final orderedPeopleOver50 = people
  .sortedBy((person) => person.age)
  .lastWhile((person) => person.age >= 50)
  .toList();

总结

Dartx 包蕴含了许多针对 Iterable、List 和其余 Dart 类型的扩大。摸索其性能的最佳形式是浏览源代码。

https://github.com/leisim/dartx

感激软件包作者 Simon Leier 和 Pascal Welsch。

https://www.linkedin.com/in/s…

https://twitter.com/passsy


© 猫哥

https://ducafecat.tech/

https://github.com/ducafecat

往期

开源

GetX Quick Start

https://github.com/ducafecat/…

新闻客户端

https://github.com/ducafecat/…

strapi 手册译文

https://getstrapi.cn

微信探讨群 ducafecat

系列汇合

译文

https://ducafecat.tech/catego…

开源我的项目

https://ducafecat.tech/catego…

Dart 编程语言根底

https://space.bilibili.com/40…

Flutter 零根底入门

https://space.bilibili.com/40…

Flutter 实战从零开始 新闻客户端

https://space.bilibili.com/40…

Flutter 组件开发

https://space.bilibili.com/40…

Flutter Bloc

https://space.bilibili.com/40…

Flutter Getx4

https://space.bilibili.com/40…

Docker Yapi

https://space.bilibili.com/40…

正文完
 0