线性进度指标在下载文件时无法管理其状态

发布于 2025-02-07 07:12:28 字数 4050 浏览 0 评论 0原文

我是Flutter的新手,目前正在开发一个从给定链接下载文件的Flutter应用程序。问题是,当只有一个链接应用程序正常运行时,但是当一个以上的链接到达文件未下载时。我在JSON文件中接收链接数据,然后解析JSON并在ListView.builder中使用这些链接。我尝试了很多,但找不到解决方案。这是屏幕的代码。主要问题是我认为状态不能很好地管理。

dsharing.json文件包含文件的名称和链接

import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
import '../services/services.dart';

class ReceiveScreen extends StatefulWidget {
 const ReceiveScreen({Key? key, }) : super(key: key);

@override
State<ReceiveScreen> createState() => _ReceiveScreenState();
 }

 class _ReceiveScreenState extends State<ReceiveScreen> {

 Map<int, double> progress = {};
 int received = 0;
 int total = 0;
 var _url = "http://192.168.1.100:50500";

 List<Receiver> receivers = [];
 @override
 initState()
 {
   super.initState();

 }

 @override
 void dispose() {
  super.dispose();
 }


@override
Widget build(BuildContext context) {
  return Scaffold(
  appBar: AppBar(
    title: const Text("Receive Files"),
  ) ,
    body: Column(
      children: [

        ElevatedButton(
            onPressed: ()async
            {
              await getUrls();
            },
            child: const Text("Get Response")
        ),

        Text(rsponse),
        FutureBuilder(
          future: getUrls(),
            builder: (context, AsyncSnapshot<Files>  snapshot)
                {
                  if(!snapshot.hasData)
                    {
                      return const Center(child:  CircularProgressIndicator());
                    }
                    Files files = snapshot.data!;
                  return ListView.builder(
                    itemCount: files.names!.length,
                    shrinkWrap: true,
                      itemBuilder: (context, index)
                      {
                        
                        return Column(
                        children: [
                          ElevatedButton(
                              onPressed: () async
                              {
                                final path = "/storage/emulated/0/Download/${files.names![index]}";
                                await Dio().download(
                                    files.urls![index],
                                    path,
                                    onReceiveProgress: (received, total)
                                    {
                                      progress[index] = received/total;
                                    }
                                );
                              },
                              child: Text("${files.names![index] } Download")
                          ),
                          LinearProgressIndicator(
                            value: progress[index],
                            minHeight: 20,
                          )
                        ],
                        );
                      }
                  );
                }
        )

     
      ],
    )
);
 }
 String rsponse = "";
 fetchDataApi() async
 {
   var response = await get(Uri.parse("$_url/dsharing.json"));

   if(response.statusCode == 200)
    {
     return jsonDecode(response.body);
    }
   }

 Future<Files> getUrls() async
 {
   var data = await fetchDataApi();
    return Files.fromJson(data, _url);
  }



  }



class Files
{
  final List? names;
  final List? urls;

  Files({ this.names, this.urls});

  factory Files.fromJson(Map map, String url)
  {
   var fileNames = [];
   String name = map['name'];
   if(name.contains(":"))
    {
     int index = name.indexOf(":") + 1;
     name = name.substring(index + 1, name.length);
     var x = name.replaceAll(" ", '^*&');
     fileNames = x.split("^*&").toList();
    }
   else
     {
      fileNames.add(name);
     }
     var x = map['data'].toString().split("|dsharing|").toList();
     var fileUrls = x.map((i) => url + "?/q="+ i).toList();
      return Files(
      names: fileNames,
      urls: fileUrls
    );
   }


 }

I am new to Flutter and am currently working on a Flutter app that downloads files from given links. The issue is that when only one link app is working fine but when more than one link arrive file does not download. I receive the link data in json file then I parsed the json and used these links inside the listview.builder. I tried very much but could not find the solution. Here is the code for the screen. Main issue is that I think state is not managed well.

dsharing.json file contain name and links of files

import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
import '../services/services.dart';

class ReceiveScreen extends StatefulWidget {
 const ReceiveScreen({Key? key, }) : super(key: key);

@override
State<ReceiveScreen> createState() => _ReceiveScreenState();
 }

 class _ReceiveScreenState extends State<ReceiveScreen> {

 Map<int, double> progress = {};
 int received = 0;
 int total = 0;
 var _url = "http://192.168.1.100:50500";

 List<Receiver> receivers = [];
 @override
 initState()
 {
   super.initState();

 }

 @override
 void dispose() {
  super.dispose();
 }


@override
Widget build(BuildContext context) {
  return Scaffold(
  appBar: AppBar(
    title: const Text("Receive Files"),
  ) ,
    body: Column(
      children: [

        ElevatedButton(
            onPressed: ()async
            {
              await getUrls();
            },
            child: const Text("Get Response")
        ),

        Text(rsponse),
        FutureBuilder(
          future: getUrls(),
            builder: (context, AsyncSnapshot<Files>  snapshot)
                {
                  if(!snapshot.hasData)
                    {
                      return const Center(child:  CircularProgressIndicator());
                    }
                    Files files = snapshot.data!;
                  return ListView.builder(
                    itemCount: files.names!.length,
                    shrinkWrap: true,
                      itemBuilder: (context, index)
                      {
                        
                        return Column(
                        children: [
                          ElevatedButton(
                              onPressed: () async
                              {
                                final path = "/storage/emulated/0/Download/${files.names![index]}";
                                await Dio().download(
                                    files.urls![index],
                                    path,
                                    onReceiveProgress: (received, total)
                                    {
                                      progress[index] = received/total;
                                    }
                                );
                              },
                              child: Text("${files.names![index] } Download")
                          ),
                          LinearProgressIndicator(
                            value: progress[index],
                            minHeight: 20,
                          )
                        ],
                        );
                      }
                  );
                }
        )

     
      ],
    )
);
 }
 String rsponse = "";
 fetchDataApi() async
 {
   var response = await get(Uri.parse("$_url/dsharing.json"));

   if(response.statusCode == 200)
    {
     return jsonDecode(response.body);
    }
   }

 Future<Files> getUrls() async
 {
   var data = await fetchDataApi();
    return Files.fromJson(data, _url);
  }



  }



class Files
{
  final List? names;
  final List? urls;

  Files({ this.names, this.urls});

  factory Files.fromJson(Map map, String url)
  {
   var fileNames = [];
   String name = map['name'];
   if(name.contains(":"))
    {
     int index = name.indexOf(":") + 1;
     name = name.substring(index + 1, name.length);
     var x = name.replaceAll(" ", '^*&');
     fileNames = x.split("^*&").toList();
    }
   else
     {
      fileNames.add(name);
     }
     var x = map['data'].toString().split("|dsharing|").toList();
     var fileUrls = x.map((i) => url + "?/q="+ i).toList();
      return Files(
      names: fileNames,
      urls: fileUrls
    );
   }


 }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文