我正在Flutter中开发一个密码管理器应用程序,同时为我的哈希函数运行以下代码片段:
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吗?
而不是这个
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