UI lags during heavy computation operation in Flutter even with async

217

Instead of this

TextButton(
  child: Text("Hash Password"),
  onPressed: () {
    hash("ThisIsTheMasterPassword").then((value) {
      print(value);
    });
})

use this

TextButton(
      child: Text("Hash Password"),
      onPressed: () async{
        hash("ThisIsTheMasterPassword").then((value) {
          print(value);
        });
    })

or

TextButton(
      child: Text("Hash Password"),
      onPressed: ()async {
       var value=await hash("ThisIsTheMasterPassword");
print(value);

    })

You can use isolate to calculate of sth out of the main thread. https://www.youtube.com/watch?v=qrFTt1NZed8

compute(hash, "ThisIsTheMasterPassword");

Further reading https://flutter.dev/docs/cookbook/networking/background-parsing

Share:
217
Yash Ahir
Author by

Yash Ahir

Updated on December 29, 2022

Comments

  • Yash Ahir
    Yash Ahir over 1 year

    I'm working on a password manager application in Flutter, while running this code snippet for my hashing function:

    import 'package:encrypt/encrypt.dart' as EncryptLib;
    import 'package:pinenacl/key_derivation.dart' as HashLib;
    
    Map<String, String> hash(String masterPass) {
      final salt = EncryptLib.IV.fromSecureRandom(16);
    
      final hashedMasterPass = HashLib.PBKDF2
          .hmac_sha512(utf8.encode(masterPass), salt.bytes, 100100, 32);
    
      return {
        "hashedMasterPass": base64.encode(hashedMasterPass),
        "salt": salt.base64,
      };
    }
    

    When I call this function from a button such as:

    TextButton(
      child: Text("Hash Password"),
      onPressed: () {
        print(hash("ThisIsTheMasterPassword"));
    })
    

    The animation for the button press completely halts and so does the rest of the UI, I read up a bit about Futures and async and came up with the following, expecting the UI to not freeze:

    Future<Map<String, String>> hash(String masterPass) async {
      final salt = EncryptLib.IV.fromSecureRandom(16);
    
      final hashedMasterPass = HashLib.PBKDF2
          .hmac_sha512(utf8.encode(masterPass), salt.bytes, 100100, 32);
    
      return {
        "hashedMasterPass": base64.encode(hashedMasterPass),
        "salt": salt.base64,
      };
    }
    

    and...

    TextButton(
      child: Text("Hash Password"),
      onPressed: () {
        hash("ThisIsTheMasterPassword").then((value) {
          print(value);
        });
    })
    

    Same results, the UI is still freezing like before, is there any way I can make this particular code not freeze the UI?