首页 > 解决方案 > 在 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(
 ...

标签: flutterflutter-provider

解决方案


使用共享首选项检查是否调用了 _getLocationData() 方法并使用 Timer.periodic(); 方法每五分钟调用一次函数。


推荐阅读