如何为 Flutter_Downloader 提供唯一 id?

时间:2021-03-16 07:59:56

标签: flutter dart dart-isolates

当按钮添加新下载时,如何为每个下载提供唯一 ID?我正在使用 Flutter_Downloader api

由于静态方法用于隔离的通信,我尝试将 is id 引用到类,但无济于事。帮助代码如下

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,
                              ),
                            ));
                          },
                        ),
                ),
              );
            },
          ),
        ]));
  }
}

当应用程序关闭时我们将如何保持下载以便能够恢复下载

1 个答案:

答案 0 :(得分:0)

<块引用>

简单、快速地生成 RFC4122 UUID。

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

相关问题