gpt4 book ai didi

variables - Dart-如何将迭代器值传递到Dart中的回调中?

转载 作者:行者123 更新时间:2023-12-03 03:41:11 25 4
gpt4 key购买 nike

我有一些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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com