Function hangs UI

371

You can use compute() method provided by the flutter that will run the code in a separate isolate(dart equivalent to threads). Something like this:

static String getHash(String input){
     return hash(input); // your code to calculate hash here.
}

String computeHash(String input){
     return await compute(getHash, input);
}

Remember that the function you pass to the compute() method has to be static, and can accept only one parameter. As isolates don't share memory so every variable to be used in the function has to be passed as a parameter. So if you have to pass multiple methods to the function, you will have to make a list of parameters.

Share:
371
Harshit Agarwall
Author by

Harshit Agarwall

Updated on December 13, 2022

Comments

  • Harshit Agarwall
    Harshit Agarwall over 1 year

    I am working with Dart, AndroidStudio, Flutter

    I need to call a function to hash my Password. The hash function takes time to execute. The code should run on press. Function is:

    String getHash(Stirng input)

    I call it a follows:

    onPressed:{
               newPass=getHash(currentPass);
              }
    

    It blocks the UI thread. The function is from some API hence it cannot be edited.

    I made an async method and called getHash() in the async funtion.

    Future<String> asyncMethodToGetHash(String input) async{
         return await geHash(input);
    }
    

    But still it blocks the UI thread. How should I call it so that UI is not blocked?