Flutter: run multiple methods

徘徊边缘 提交于 2021-01-01 06:41:59

问题


I have a big problem. If I want to encrypt my video file, my application is freezing until that method finishing. But there is no error. How can I code my application does not freeze. thanks.

Future sifrele() async {
  String realPath =
    "/storage/emulated/0/Android/data/com.android.xxxx/files";

    var crypt = AesCrypt('sefa');
    try {
      crypt.setOverwriteMode(AesCryptOwMode.on);
      String encFilepaths = await crypt.encryptFile(
          realPath + '/WhatCarCanYouGetForAGrand.mp4',
          realPath + '/video.mp4.aes');
      print('The encryption has been completed successfully.');
      //print('Encrypted file: $encFilepath');

    } on AesCryptException catch (e) {
      if (e.type == AesCryptExceptionType.destFileExists) {
        print('The encryption has been completed unsuccessfully.');
      }
      return;
    }
  }

回答1:


Change the function type of your function from Future to FutureOr, add a parameter to the function (even if you don't need it) and use compute. it will work perfectly.

Before

Future sifrele() async {

After

FutureOr sifrele(String para) async {

compute

  doTheEncryption() {
    compute(sifrele, 'Pass the value of the parameter here if you need it');
  }

Another one important thing the definition of the function sifrele must be a top level, meaning not inside the class, put it outside the class. The function doTheEncryption() (or whaterver you name it) maybe inside the class no problem.




回答2:


Try this. Maybe will work if you put code for encryption in isolate. For that use method compute.

void _startEncrypting()
{
compute(sifrele, /** Here put your parameters if you need them **/);
}

sifrele() async {
String realPath = "/storage/emulated/0/Android/data/com.android.xxxx/files";

var crypt = AesCrypt('sefa');
try {
  crypt.setOverwriteMode(AesCryptOwMode.on);
  String encFilepaths = await crypt.encryptFile(
      realPath + '/WhatCarCanYouGetForAGrand.mp4',
      realPath + '/video.mp4.aes');
  print('The encryption has been completed successfully.');
  //print('Encrypted file: $encFilepath');

} on AesCryptException catch (e) {
  if (e.type == AesCryptExceptionType.destFileExists) {
    print('The encryption has been completed unsuccessfully.');
  }
  return;
}

}



来源:https://stackoverflow.com/questions/64427551/flutter-run-multiple-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!