Can anyone create/add a simple "map indexed" method on List on Flutter?

huangapple go评论85阅读模式
英文:

Can anyone create/add a simple "map indexed" method on List on Flutter?

问题

根据Stack Overflow上的一些答案,我尝试创建一个List的“扩展”,用于mapIndexed,即一个同时传递索引的map函数。以下是我得到的代码示例:

mixin MapIndexed on List {
  Iterable<U> mapIndexed<T, U>(U Function(T e, int i) f) {
    int i = 0;
    return map<U>((it) { final t = i; i++; return f(it, t); });
  }
}

问题是,我不知道如何调用它。我基于iOS Swift的扩展概念创建了这个。最终,我只是希望能够这样调用 result = myList.mapIndexed((element, index) => doMapping);。我应该如何正确地实现这个?根据当前的方式,我可以通过以下函数来实现最接近的效果:

Iterable<U> mapIndexed<T, U>(List<T> list, U Function(T e, int i) f) {
  int i = 0;
  return list.map<U>((it) { final t = i; i++; return f(it, t); });
}

result = mapIndexed(list, (element, index) => doMapping);

请注意,以上是您提供的代码示例的翻译。如果您需要进一步的帮助或解释,请随时提问。

英文:

Based on some answers on Stack Overflow, I tried to create an "extension" of List for mapIndexed, that is, a map function which also passes index. This is what I got:

mixin MapIndexed on List {

  Iterable&lt;U&gt; mapIndexed&lt;T, U&gt;(U Function(T e, int i) f) {
    int i = 0;
    return map&lt;U&gt;((it) { final t = i; i++; return f(it, t); });
  }

}

The problem is, I don't know how to call this. I created this based on the iOS Swift's extension concept. Ultimately, I just want that I can call result = myList.mapIndexed((element, index) =&gt; doMapping);. How can I do this correctly? The way it is right now, the closest I can do to achieve this is by function:

Iterable&lt;U&gt; mapIndexed&lt;T, U&gt;(List&lt;T&gt; list, U Function(T e, int i) f) {
  int i = 0;
  return list.map&lt;U&gt;((it) { final t = i; i++; return f(it, t); });
}

result = mapIndexed(list, (element, index) =&gt; doMapping);

答案1

得分: 2

以下是翻译好的代码部分:

尝试以下内容:

extension MapIndexed on Iterable {
  Iterable<U> mapIndexed<T, U>(U Function(T e, int i) f) {
    int i = 0;
    return map<U>((it) {
      final t = i;
      i++;
      return f(it, t);
    });
  }
}

使用它进行测试:

print([1,3,5].mapIndexed((value, index) => index * 10 + value));

您应该会看到输出:

(1, 13, 25)

请注意,我只翻译了代码部分,没有包括问题中的其他内容。

英文:

try the following:

extension MapIndexed on Iterable {
    Iterable&lt;U&gt; mapIndexed&lt;T, U&gt;(U Function(T e, int i) f) {
    int i = 0;
    return map&lt;U&gt;((it) { final t = i; i++; return f(it, t); });
  }
}

with that you could test it by:

print([1,3,5].mapIndexed((value, index) =&gt; index * 10 + value));

you should see the output:

(1, 13, 25)

huangapple
  • 本文由 发表于 2020年1月6日 16:35:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/59608920.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定