Search code examples
fluttersharedpreferences

flutter/ how to save geopoint using shared preferences


I want to know how to save user's geopoint using shared preferences in my flutter app. It has 2 values(lat, long), but the following code was all I could write, which didn't work.

     static String sharedPreferenceUserGeopointKey = "USERGEOPOINTKEY";

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

later I retrieve this data like this;

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;

I can't put result into GeoPoint typed geopoint object, I can I do this?


Solution

  • You need to call twice setDouble with different key.

    Or try to use setStringList() method of shared preferences class.
    In this case, you need to change from double latitude, logitude to list string.

         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();