Flutter:如何将同步静态方法与异步非静态方法同步



当我启动应用程序时,它应该检查是否可以使用生物识别身份验证(指纹/人脸id(。我有一个检查这个的类,登录页面需要它的结果

class LocalAuthenticationUtil with ChangeNotifier {
static LocalAuthentication _auth = LocalAuthentication();
static List<BiometricType> biometricTypes;
static bool haveBiometrics = true;
bool _biometricAuthenticated = true;
static LocalAuthenticationUtil _instance;
static LocalAuthenticationUtil getInstance() {
if (_instance == null) {
_instance = LocalAuthenticationUtil();
print("GetInstance CanCheckBiometrics before");
_instance._canCheckBiometrics();
print("GetInstance CanCheckBiometrics after");
if (haveBiometrics) {
_instance.addListener(() {
_instance.authenticate();
});
_instance.authenticate();
}
}
return _instance;
}
Future<void> _canCheckBiometrics() async {
print("CanCheckBiometrics before");
haveBiometrics = await _auth.canCheckBiometrics;
print("CanCheckBiometrics after");
if (haveBiometrics) {
biometricTypes = await _auth.getAvailableBiometrics();
}
}
set biometricAuthenticated(bool value) {
if (_biometricAuthenticated != value) {
_biometricAuthenticated = value;
notifyListeners();
}
}

当代码运行时,结果是:

I/flutter (23495): GetInstance CanCheckBiometrics before
I/flutter (23495): CanCheckBiometrics before
I/flutter (23495): GetInstance CanCheckBiometrics after
I/flutter (23495): CanCheckBiometrics after

而我想发生的顺序是:

I/flutter (23495): GetInstance CanCheckBiometrics before
I/flutter (23495): CanCheckBiometrics before
I/flutter (23495): CanCheckBiometrics after
I/flutter (23495): GetInstance CanCheckBiometrics after

您不是await_instance._canCheckBiometrics();

Dart同步执行,直到它达到await,这时函数立即返回,但";记得它在哪里";,因此它可以在awaitFuture完成时继续它停止的地方:

这里,当您调用_instance._canCheckBiometrics()时,它会立即运行第一个print语句,然后命中await _auth.canCheckBiometrics,并立即返回代表_instance._canCheckBiometrics()结果的Future

只需将_instance._canCheckBiometrics()替换为await _instance._canCheckBiometrics()就可以了。

顺便说一句,你可以创建一个analysis_options.yaml文件来为你的项目定制你的过梁警告。当您在没有await的异步上下文中有一个返回Future的函数时,一个名为unawaited_futures的函数会特别警告您。这通常是一个错误,但如果确定的话,您可以手动取消它。这个规则通常有助于捕捉这样的错误。要使用过梁,请检查:https://dart.dev/guides/language/analysis-options#enabling-短绒规则

cameron1024是对的。您需要做的是创建一个StatefulWidget,它将在检查完成后重定向用户。

class AuthWidget extends StatefulWidget {
AuthWidget({Key key}) : super(key: key);
@override
_AuthWidgetState createState() => _AuthWidgetState();
}
class _AuthWidgetState extends State<AuthWidget> {
@override
void initState() { 
super.initState();
checkBiometrics(); // perform the check asynchronously and then use Navigator.of(context).push/replace
}
@override
Widget build(BuildContext context) {
// Display a loader while checking
return CircularProgressIndicator();
}
}

最新更新