简体   繁体   English

如何为 Flutter_Downloader 提供唯一 ID?

[英]How provide unique id for Flutter_Downloader?

How can unique ID be provided for each download when new download is added by the button?通过按钮添加新下载时,如何为每次下载提供唯一 ID? I'm using Flutter_Downloader api我正在使用Flutter_Downloader api

Since static method is used for communication of isolates, i have tried referencing is id to the class but to no avail.由于 static 方法用于隔离物的通信,因此我尝试将 id 引用到 class 但无济于事。 Help the code is below帮助代码如下

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<String> saveList = [];
  bool isdown = false;
  ReceivePort _port = ReceivePort();
  int progress = 0;
  String id;
  DownloadTaskStatus status;
  int progresscomplite = 100;

  @override
  void initState() {
    super.initState();
    _downloadListener();
  }

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

  void disp() {
    IsolateNameServer.removePortNameMapping('downloader');
  }

  static void downloadCallback(
      String id, DownloadTaskStatus status, int progress) {
    final SendPort send = IsolateNameServer.lookupPortByName('downloader' );
    send.send([id, status, progress]);
  }

  _downloadListener() {
    bool isSuccess =
        IsolateNameServer.registerPortWithName(_port.sendPort, 'downloader');
    if (!isSuccess) {
      disp();
      _downloadListener();
      return;
    }
    IsolateNameServer.registerPortWithName(_port.sendPort, 'downloader');
    _port.listen((dynamic data) {
      setState(() {
        isdown = true;
        id = data[0];
        status = data[1];
        progress = data[2];

       

      });

      print('$progress');
    });
    FlutterDownloader.registerCallback(downloadCallback);
  }




  void _download() async {
    String _localPath =
        (await findLocalPath()) + Platform.pathSeparator + 'Example_Downloads';

    final savedDir = Directory(_localPath);
    bool hasExisted = await savedDir.exists();
    if (!hasExisted) {
      savedDir.create();
    }
    String _url =
        "https://upload.wikimedia.org/wikipedia/commons/e/e4/GatesofArctic.jpg";
    final download = await FlutterDownloader.enqueue(
      url: _url,
      savedDir: _localPath,
      showNotification: true,
      openFileFromNotification: true,
    );
  }

  Future<String> findLocalPath() async {
    final directory =
        // (MyGlobals.platform == "android")
        // ?
        await getExternalStorageDirectory();
    // : await getApplicationDocumentsDirectory();
    return directory.path;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: isdown
          ? Column(
              children: [
                Center(
                  child: LinearProgressIndicator(
                    value: progress / 100,
                    minHeight: 10,
                  ),
                ),
                MaterialButton(
                  onPressed: () async {
                    await FlutterDownloader.pause(taskId: id);
                  },
                  child: Text('pause'),
                ),
                MaterialButton(
                  onPressed: () async {
                    await FlutterDownloader.resume(taskId: id);
                  },
                  child: Text('resume'),
                )
              ],
            )
          : Text('no data'),
      floatingActionButton: FloatingActionButton(
        onPressed: _download,
        child: Icon(Icons.file_download),
      ),
    );
  }
}

class SecondTab extends StatefulWidget {
  SecondTab({Key key}) : super(key: key);

  @override
  _SecondTabState createState() => _SecondTabState();
}

class _SecondTabState extends State<SecondTab> {
  var files;
  // ShareModel share;

  // _SecondTabState({this.share});

  void getFiles() async {
    //asyn function to get list of files
    //List<StorageInfo> storageInfo = await PathProviderEx.getStorageInfo();
    //var root = storageInfo[0].rootDir; //storageInfo[1] for SD card, geting the root directory
    var fm = FileManager(root: Directory('/storage/emulated/0/VideoTube')); //
    files = await fm.filesTree(
        // fm.dirsTree() for directory/folder tree list
        excludedPaths: ["/storage/emulated/0/VideoTube/"],
        extensions: ["mp4"] //optional, to filter files, remove to list all,
        //  remove this if your are grabbing folder list
        );

    setState(() {}); //update the UI
  }

  @override
  void initState() {
    getFiles(); //call getFiles() function on initial state.
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    // super.build(context);
    return Scaffold(
        appBar: AppBar(
            title: Text("File/Folder list from SD Card"),
            backgroundColor: Colors.redAccent),
        body: Column(children: <Widget>[
         
          FutureBuilder(
            builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
              return Flexible(
                flex: 9,
                child: Container(
                  child: files == null
                      ? Text("Searching Files")
                      : ListView.builder(
                          //if file/folder list is grabbed, then show here
                          itemCount: files?.length ?? 0,
                          itemBuilder: (context, index) {
                            return Card(
                                child: ListTile(
                              title: Text(files[index].path.split('/').last),
                              leading: Icon(Icons.video_label),
                              trailing: Icon(
                                Icons.delete,
                                color: Colors.redAccent,
                              ),
                            ));
                          },
                        ),
                ),
              );
            },
          ),
        ]));
  }
}

Also how will we persist the downloads when the app is closed so as be able to resume the downloads此外,当应用程序关闭时,我们将如何保持下载以便能够恢复下载

Simple, fast generation of RFC4122 UUIDs.简单、快速地生成 RFC4122 UUID。

you can use https://pub.dev/packages/uuid你可以使用https://pub.dev/packages/uuid

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM