加密过程使 flutter 应用程序冻结直到完成

问题描述 投票:0回答:1

我正在制作一个 flutter 应用程序,用户可以在其中观看或下载视频 下载视频后,我想对其进行加密然后存储,因为我不希望用户能够共享它。 加密过程正在正确执行,但是当它启动时,应用程序会冻结大约 10 秒,然后才完成,然后应用程序解冻 我尝试了多种加密方法,但结果相同 我在这里读到,使用“compute”方法并将函数类型更改为“FutureOr”可以解决问题。但是,我似乎无法正确使用它。 任何帮助将不胜感激。

  Future<void> downloadVideo(String url) async {
    var appDocDir = await getExternalStorageDirectory();
    String appDocPath = appDocDir!.path;
    String filePath = '$appDocPath/Videos/${url.split('/').last}';

    try {
      var request = await HttpClient().getUrl(Uri.parse(url));
      var response = await request.close();
      List<int> bytes = [];
      int downloaded = 0;
      int total = response.contentLength!;
      response.listen(
        (List<int> newBytes) {
          bytes.addAll(newBytes);
          downloaded += newBytes.length;
          downloadProgress.value = downloaded / total;
          print("Download progress: ${downloadProgress.value}");
        },
        onDone: () async {
          // Generate encryption key and IV
          final key = encrypt.Key.fromSecureRandom(32);
          final iv = encrypt.IV.fromSecureRandom(16);

          // Encrypt the video bytes
          final encrypter =
              encrypt.Encrypter(encrypt.AES(key, mode: encrypt.AESMode.cbc));
          final encryptedBytes = encrypter.encryptBytes(bytes, iv: iv).bytes;

          // Store the key and IV securely
          final storage = FlutterSecureStorage();
          await storage.write(key: 'key_$filePath', value: key.base64);
          await storage.write(key: 'iv_$filePath', value: iv.base64);

          // Save the encrypted video
          File file = File(filePath);
          await file.writeAsBytes(encryptedBytes);
          print("Download completed: $filePath");
        },
        onError: (e) {
          print("Error downloading video: $e");
        },
        cancelOnError: true,
      );
    } catch (e) {
      print("Error downloading video: $e");
    }
  }
flutter dart encryption
1个回答
0
投票

默认情况下,Dart 在单个线程中执行所有任务。因此,当启动大型计算过程时,您可能会在 UI 中遇到延迟。

在这种情况下,您可以使用隔离将重负载移至完全不同的线程处理。您可以简单地使用

Isolate.run
方法来执行此操作。不要直接调用
downloadVideo
方法,而是在主线程中将其调用为以下代码:

  final url = "..."; // Your download URL

  Isolate.run(() async {
    await downloadVideo(url);
  });

以下是有关 YouTube 上的 Isolates 的更多信息 | FlutterDart 文档

希望这有帮助:)

© www.soinside.com 2019 - 2024. All rights reserved.