当用户在flutter中从设置屏幕导航回应用程序时,检测方法



我使用以下代码将用户导航到设置屏幕,以手动允许位置权限:

PermissionHandler().openAppSettings();

一旦用户允许这个权限,我就会检查权限是否被授予。如果获得授权,我将允许用户导航到下一个屏幕。

@override
void didChangeAppLifecycleState(AppLifecycleState state) {
checkPermission(); //this will check the status of permission when the user returns back from the settings page.
}

checkPermission() async {
var location = Location();
bool _permission = false;
bool serviceStatus = await location.serviceEnabled();
if (serviceStatus) {
print("enable");
_permission = await location.requestPermission();
print("Permission result: $_permission");
if (_permission) {
// Navigate to next screen
}else{
print("permission not enable");
}
} else {
print("not enable");
}
}

问题是didChangeAppLifecycleState方法总是被调用用于屏幕上的任何操作。当用户从后台导航到前台应用程序或从设置屏幕导航到屏幕时,我应该如何检测状态。以下是状态,但没有。这是有用的。

  • resumed
  • inActivate
  • paused
  • detached

您的代码只缺少一件事:您没有使用state变量来检查当前应用程序的生命周期状态。在运行checkPermission()函数之前,您可以简单地使用它来检查当前应用程序状态。

@override
void didChangeAppLifecycleState(AppLifecycleState state) {
// If user resumed to this app, check permission
if(state == AppLifecycleState.resumed) {
checkPermission();
}
}

现在,只有当当前应用程序的生命周期状态为resumed时,才会调用checkPermission()

最新更新