【问题标题】:Shared preference save location address from geolocator共享偏好从地理定位器中保存位置地址
【发布时间】:2020-05-06 13:27:08
【问题描述】:

我能够使用地理定位器获取当前位置,但我想缓存和恢复字符串地址,而不使用地理定位器中的 lastKnownLocation。我正在使用共享首选项,但无法使其正常工作。我在其他代码上多次使用共享偏好,但使用地理定位器有点复杂。我对颤振/飞镖超级新手

代码:

  final Geolocator geolocator = Geolocator()..forceAndroidLocationManager;
  Position _currentPosition;
  String _currentAddress;
  String _locationCache;
  String key = "location_cache";

  @override
  void initState() {
    super.initState();
    _getCurrentLocation();
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text("current location = " + _currentAddress),
            Text("last location = " + __locationCache) // HERE GET STORED DATA ISNT WORKING
          ],
        ),
      ),
    );
  }

  _getCurrentLocation() {
    geolocator
        .getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
        .then((Position position) {
      setState(() {
        _currentPosition = position;
      });

      _getAddressFromLatLng();
    }).catchError((e) {
      print(e);
    });
  }

  _getAddressFromLatLng() async {
    try {
      List<Placemark> p = await geolocator.placemarkFromCoordinates(
          _currentPosition.latitude, _currentPosition.longitude);

      Placemark place = p[0];

      setState(() {
        _currentAddress = "${place.country}";
      });

      saveAddress();
    } catch (e) {
      print(e);
    }
  }

  Future<bool> saveAddress() async { 
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return await prefs.setString(key, _currentAddress);
  }

  Future<String> retrieveAddress() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    //Return String
    return prefs.getString(key) ?? "";
  }

  loadAddress() {
    retrieveAddress().then((value) {
      setState(() {
        _locationCache = value;
      });
    });
  }
}

这里是没有 _locationCache 的工作代码:

感谢您的宝贵时间

【问题讨论】:

    标签: flutter caching path geolocation sharedpreferences


    【解决方案1】:

    如果我对您的理解正确,您想要完成的是存储您捕获的最后一个地址并在您没有​​激活 gps 时检索它。
    为此,您可以使用SharedPreferencesSQLite,只需查看有关如何使用它们的文档即可。

    【讨论】:

    • 我编辑了上面包含共享首选项的代码,但仍然没有成功
    【解决方案2】:

    找到了解决方案。只需将 loadAddress() 函数替换为

    void save() {
        String address = _currentAddress;
        saveAddress(address);
      }
    
    void _updateName(String address) {
      setState(() {
        this.locationCache = address;
      });
    }

    然后将retrieveAddress().then(updateName) 放入initState()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-13
      • 1970-01-01
      相关资源
      最近更新 更多