作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一些Dart / Flutter代码,基本上可以做到这一点:
for(int i = 0; i < dataArray.length; i++){
int curr = i;
table.add(
new DataRow(
...
onSelectChanged: (bool selected){
DataRow toSwap = table[curr];
/*This is how I "get" a row to select it,
as there is no getter for the "checked" property*/
...
}
)
);
}
curr
变量,但是,在方法中调用它时,它反射(reflect)了迭代器的最终值。在Dart中添加回调时如何使用
curr
的值?
最佳答案
我假设您在发布代码之前对其进行了修改..如jamesdlin comment所示,您的代码可以使用。因此,要解决您的原始问题,您只需为每次迭代创建一个新变量,我假设您的原始代码在循环外部定义了该变量。
即,通过@jamesdlin example显示:
// working as expected
for (int i = 0; i < 10; i += 1) {
final int current = i;
functionList.add(() => print('$i $current')); // 0 0, 1 1, 2 2, ...
}
// current will be updated
int current;
for (int i = 0; i < 10; i += 1) {
current = i;
functionList.add(() => print('$i $current')); // 0 9, 1 9, 2 9, ...
}
final
,因此无论如何您都不愿意在循环外创建变量。
关于variables - Dart-如何将迭代器值传递到Dart中的回调中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55681821/
我是一名优秀的程序员,十分优秀!