颤动/如何使用共享首选项保存地理点

flutter/ how to save geopoint using shared preferences

我想知道如何在我的 flutter 应用程序中使用共享首选项来保存用户的地理点。它有 2 个值(纬度、经度),但下面的代码是我所能写的,但没有用。

     static String sharedPreferenceUserGeopointKey = "USERGEOPOINTKEY";

     static Future<bool> saveUserGeopointSharedPreference(var geopoint) async {
     SharedPreferences preferences = await SharedPreferences.getInstance();
     return await preferences.setDouble(
     sharedPreferenceUserGeopointKey, geopoint);
     }

稍后我会像这样检索这些数据;

static Future<dynamic> getUserGeopointSharedPreference() async {
  SharedPreferences preferences = await SharedPreferences.getInstance();
  double mylat = 
preferences.getDouble(sharedPreferenceUserGeopointLatKey);
  double mylong = 
preferences.getDouble(sharedPreferenceUserGeopointLongKey);
  return true;
}

bool result = await getUserGeopointSharedPreferences();
GeoPoint geopoint = result;

我无法将 result 放入 GeoPoint 类型的地理点对象中,我可以这样做吗?

您需要使用不同的密钥调用两次 setDouble。

或者尝试使用共享首选项的 setStringList() 方法 class.
在这种情况下,您需要将双纬度、经纬度更改为列表字符串。

     static String sharedPreferenceUserGeopointLatitudeKey = "USERGEOPOINT_LATITUDE_KEY";
     static String sharedPreferenceUserGeopointLogitudeKey = "USERGEOPOINT_LONGITUDE_KEY";

     static Future<bool> saveUserGeopointSharedPreference(var lat, var long) async {
        SharedPreferences preferences = await SharedPreferences.getInstance();
        await preferences.setDouble(
           sharedPreferenceUserGeopointLatitudeKey, lat);
        await preferences.setDouble(
           sharedPreferenceUserGeopointLogitudeKey, long);
        return true
     }
static Future<GeoPoint> getUserGeopointSharedPreference() async {
  SharedPreferences preferences = await SharedPreferences.getInstance();
  double mylat = 
preferences.getDouble(sharedPreferenceUserGeopointLatKey);
  double mylong = 
preferences.getDouble(sharedPreferenceUserGeopointLongKey);
  return GeoPoint.fromLatLng(name: 'Position', point: LatLng(mylat, mylong);
}

GeoPoint geopoint = await getUserGeopointSharedPreferences();