我使用应用程序中的健康包来同步我的应用程序和Google / Apple之间的数据。到目前为止,我只有,如果我授予所有必要的权限,它的工作非常好。但我发现了一件奇怪的事我想不出怎么解决它。到目前为止,我只实现并测试了与Apple Health的集成。
因此,我检查该应用程序是否有权限读取或写入特定的数据类型,然后我读取它或将其写入Apple Health。如果授予了权限,并且读/写操作成功,我想向用户展示这一点。如果没有授予许可,我也想向用户展示这一点,这样他就知道出了什么问题。在包的HealthFactory类中,有我调用的requestAuthorization方法来检查用户是否有权限。我期望的行为是,如果未授予权限,则如果未授予该权限,则该方法的返回值为false。但是,它始终是true。而且,getHealthDataFromTypes和writeHealthData方法并不能真正指示权限是否被授予。
我实现了几个方法来展示:
class TestScreen extends StatelessWidget {
TestScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ElevatedButton(
child: Text("Health Permission"),
onPressed: () async {
final HealthFactory _health = HealthFactory();
await Permission.activityRecognition.request();
bool permission = await _health.requestAuthorization(
[HealthDataType.WEIGHT],
permissions: [HealthDataAccess.READ_WRITE],
);
print(permission);
},
),
ElevatedButton(
child: Text("Read Data"),
onPressed: () async {
final HealthFactory _health = HealthFactory();
DateTime untilDate = DateTime.now();
DateTime fromDate = DateTime(1970);
try {
List<HealthDataPoint> healthData =
await _health.getHealthDataFromTypes(
fromDate,
untilDate,
[HealthDataType.WEIGHT],
);
return print(healthData.toString());
} on Exception catch (e) {
print(e.toString());
rethrow;
}
},
),
ElevatedButton(
child: Text("Write Data"),
onPressed: () async {
final HealthFactory _health = HealthFactory();
try {
bool success = await _health.writeHealthData(
80,
HealthDataType.WEIGHT,
DateTime.now(),
DateTime.now(),
);
print(success);
} on Exception catch (e) {
print(e.toString());
}
},
),
],
),
),
);
}
}这是我的测试屏幕。
第一个按钮请求数据类型权重的READ_WRITE权限。在第一次调用时,这个窗口弹出:

当我在左上角单击“不允许”时,权限不会被授予,但是该方法仍然返回true。如果进入设置,无论是否激活权限,它总是返回true。
第二个按钮应该读取来自Apple Health的体重数据。如果获得许可,一切正常。如果未授予权限,它仍然“工作”,但jsut返回一个空列表。这很糟糕,因为我无法说明它是失败了,还是Apple Health没有任何重量数据。
第三个按钮应该将重量数据写入Apple Health。如果获得许可,同样,一切都很好。如果未授予该权限,则mehod将返回false,并且不会写入任何内容。这已经是一个比读取操作更好的指示符,但我仍然不能指出权限是未授予还是其他错误。
因此,我的问题是:是否有任何方法在代码级别指示权限是否已被授予?如果同步成功,我真的需要这样做给用户看,如果没有,为什么不工作。
发布于 2022-04-27 17:03:18
请查看文档https://pub.dev/documentation/health/latest/health/HealthFactory/hasPermissions.html,也请验证,但在IOS上,它似乎返回null。Apple保护此字段,该包返回null,因为Apple HealthKit不会透露如果出于隐私考虑,数据类型已被授予读访问权,此方法只能返回null来表示未确定的状态,如果使用读取或READ_WRITE访问在iOS上调用它。
https://stackoverflow.com/questions/72032221
复制相似问题