Flutter: run multiple methods

670 Views Asked by At

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;
    }
  }
2

There are 2 best solutions below

1
On BEST ANSWER

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.

1
On

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;
}

}