英文:
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<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); });
}
}
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) => 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<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);
答案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<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); });
}
}
with that you could test it by:
print([1,3,5].mapIndexed((value, index) => index * 10 + value));
you should see the output:
(1, 13, 25)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论