【问题标题】:How to Use Download Functionality in a while Loop?如何在while循环中使用下载功能?
【发布时间】:2021-01-24 06:47:15
【问题描述】:

我有下面的代码,目的是在每个图像下方放置一个下载按钮,并在单击时下载该特定图像。但是,当我运行代码时,对于所有按钮,它都试图下载第 9 个图像,而循环运行直到 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);
}

【问题讨论】:

    标签: loops flutter while-loop


    【解决方案1】:

    实际上,在循环结束时,i9,这就是为什么您会看到自己的行为。您必须制作i 的本地副本,以便该变量保持在它被捕获时为循环所具有的值:

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

    【讨论】:

    • 非常感谢! :)
    猜你喜欢
    • 1970-01-01
    • 2013-01-24
    • 1970-01-01
    • 1970-01-01
    • 2013-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多