如何在while循环中使用下载功能



我有下面的代码,目标是在每个图像下面放一个下载按钮,并在点击时下载特定的图像。然而,当我运行代码时,对于所有按钮,它都试图下载图像编号9,而循环运行till仅I=8,即8个图像。请帮助如何解决此问题?

Widget getWidgets(int index, String name) {
List<Widget> list = new List<Widget>();
int i = 1;
while (i <= index) {
list.add(new Column(
children: <Widget>[
SizedBox(
height: 15.0,
),
BeforeAfter(
beforeImage: Image.asset(
'assets/$name/OG$i.jpg',
//fit: BoxFit.cover,
),
afterImage: Image.asset(
'assets/$name/$i.jpg',
//fit: BoxFit.cover,
),
isVertical: false,
),
SizedBox(
height: 10.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("$name $i",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 17,
fontFamily: 'Raleway',
color: Colors.black)),
Container(
margin: EdgeInsets.only(left: 100.0),
width: 120.0,
height: 35.0,
child: FlatButton(
onPressed: () async {
final status = await Permission.storage.request();
if (status.isGranted) {
final externalDir = await getExternalStorageDirectory();
FlutterDownloader.enqueue(
url: 'assets/$name/$i.dng',
savedDir: externalDir.path,
fileName: '$name$i.dng',
showNotification: true,
openFileFromNotification: true,
);
} else {
print("Permission Denied");
}
},
child: Text('Download',
style: TextStyle(color: Colors.black, fontSize: 17)),
textColor: Colors.white,
shape: RoundedRectangleBorder(
side: BorderSide(
color: Colors.teal, width: 2, style: BorderStyle.solid),
borderRadius: BorderRadius.circular(50)),
),
),
],
),
],
));
i++;
}
return Column(children: list);
}

实际上,在循环的末尾,i就是9,这就是为什么您可以看到您的行为。您必须制作i的本地副本,以便此变量在捕获时保持为循环所具有的值:

while (i <= index) {
final localIndex = i;
// rest of your code, use localIndex here instead of i
i++;
}   

最新更新