【问题标题】:UI lags during heavy computation operation in Flutter even with async即使使用异步,在 Flutter 中的繁重计算操作期间 UI 也会滞后
【发布时间】:2021-07-02 14:23:11
【问题描述】:

我正在 Flutter 中开发一个密码管理器应用程序,同时为我的哈希函数运行这段代码 sn-p:

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

当我从一个按钮调用这个函数时,例如:

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

按钮按下的动画完全停止,UI 的其余部分也完全停止,我阅读了一些关于 Futures 和 async 的内容并提出以下内容,希望 UI 不会冻结:

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

还有……

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

同样的结果,UI 仍然像以前一样冻结,有什么办法可以让这个特定的代码不冻结 UI?

【问题讨论】:

    标签: flutter dart asynchronous encryption cryptography


    【解决方案1】:

    不是这个

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

    使用这个

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

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

    您可以使用isolate 在主线程之外计算某事。 https://www.youtube.com/watch?v=qrFTt1NZed8

    compute(hash, "ThisIsTheMasterPassword");
    

    延伸阅读https://flutter.dev/docs/cookbook/networking/background-parsing

    【讨论】:

    • 谢谢,insolate 正是我想要的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-07
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多