flutter - 在 initState 中获取位置数据
问题描述
我需要获取用于计算用户与其他位置之间距离的位置数据。这是在应用程序的主页上,我不想在每次页面加载时都这样做,这就是为什么我设置一个时间戳并且只有在五分钟过去后才会抓取位置。
我现在在主页中是这样的:
LocationData _currentPosition;
@override
void initState() {
super.initState();
_getLocationData();
}
_getLocationData() async {
final content = Provider.of<Content>(context.read());
final _timestamp = DateTime.now().millisecondsSinceEpoch;
final _contentTimestamp = content.homeTimestamp;
if ((_contentTimestamp == null) ||
((_timestamp) - _contentTimestamp) >= 300000) {
try {
_locationData = await location.getLocation();
content.homeTimestamp = _timestamp;
setState(() {
_currentPosition = _locationData;
});
} on Exception catch (exception) {
print(exception);
} catch (error) {
print(error);
}
}
}
我存储时间戳是Provider
因为我希望它在用户离开主页并返回时保持不变。不知道如何设置它notifyListeners()
int _homeTimestamp;
int get homeTimestamp => _homeTimestamp;
set homeTimestamp(int newValue) {
_homeTimestamp = newValue;
notifyListeners();
}
我的问题是有时该位置没有被存储并且页面没有加载。有一个更好的方法吗?
我正在考虑在正文中添加一个 FutureBuilder,但这意味着每次用户加载页面时都会检索该位置,或者我可以只在正文中进行时间戳检查而不是FutureBuilder
一直加载,但是似乎不对。
body: _currentPosition == null
? Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
height: 20.0,
width: 20.0,
child: CircularProgressIndicator(),
),
SizedBox(
width: 10.0,
),
Text("Getting your location..."),
],
),
)
: Column(
...
解决方案
使用共享首选项检查是否调用了 _getLocationData() 方法并使用 Timer.periodic(); 方法每五分钟调用一次函数。
推荐阅读
- regex - 如何排除前面字符与正则表达式中指定的字符不同的字符?
- visual-studio - 如何使用多个参数测试 Azure 函数
- android - 如何修复模拟器上的 apiAvailability.isGooglePlayServicesAvailable 行为不端
- mysql - PrestaShop 无缘无故地在 /tmp 中创建 #sql_ 文件
- typo3 - TYPO3 ConnectionPool 找到文件引用的uid后的文件并更新数据
- json - JQ:Bigint 数字精度
- java - AdMob 自定义事件插页式广告不显示
- javascript - 将 javascript 变量插入交易电子邮件中的 href 链接
- node.js - 如何防止模块在 NodeJS 中被加载到生产环境中?
- eclipse - Eclipse 中的 JavaFX 设置:“JavaFX 11+ SDK”选项是干什么用的?