es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

Flutter / Cómo guardar Geopoint usando SharedPreferences.

Quiero saber cómo guardar el geopunto del usuario usando shared preferences en mi aplicación de Flutter. Tiene 2 valores (latitud, longitud), pero el siguiente código fue todo lo que pude escribir, y no funcionó.

Más tarde recupero estos datos así:

No puedo poner “result” en un objeto geopoint de tipo GeoPoint, ¿cómo puedo hacer esto?

Tags:  ,

Answer

  1. Avatar for davy.ai

    Para guardar el geopunto de un usuario usando shared preferences en una aplicación Flutter, se puede modificar el código existente de la siguiente manera:

    static String sharedPreferenceUserGeopointLatKey = "USERGEOPOINTLATKEY";
    static String sharedPreferenceUserGeopointLongKey = "USERGEOPOINTLONGKEY";
    
    static Future<bool> saveUserGeopointSharedPreference(double lat, double long) async {
      SharedPreferences preferences = await SharedPreferences.getInstance();
      await preferences.setDouble(sharedPreferenceUserGeopointLatKey, lat);
      await preferences.setDouble(sharedPreferenceUserGeopointLongKey, long);
      return true;
    }
    
    static Future<geopoint> getUserGeopointSharedPreference() async {
      SharedPreferences preferences = await SharedPreferences.getInstance();
      double mylat = preferences.getDouble(sharedPreferenceUserGeopointLatKey);
      double mylong = preferences.getDouble(sharedPreferenceUserGeopointLongKey);
      if (mylat == null || mylong == null) {
        return null;
      }
      return GeoPoint(mylat, mylong);
    }
    

    En este código, hemos agregado claves separadas para la latitud y longitud del geopunto del usuario. La función saveUserGeopointSharedPreference ahora toma dos argumentos para la latitud y longitud, y las establece por separado en shared preferences. La función getUserGeopointSharedPreference ahora devuelve un objeto Future<geopoint>, que se construye a partir de los valores separados de latitud y longitud recuperados de shared preferences. También hemos agregado una verificación de valores nulos en caso de que las preferencias no se hayan establecido todavía.

    Para usar este código, se puede llamar a saveUserGeopointSharedPreference de la siguiente manera:

    await saveUserGeopointSharedPreference(37.7749, -122.4194);
    

    Y llamar a getUserGeopointSharedPreference de la siguiente manera:

    GeoPoint geopoint = await getUserGeopointSharedPreference();
    if (geopoint != null) {
      print("Latitud: ${geopoint.latitude}, Longitud: ${geopoint.longitude}");
    } else {
      print("Geopunto no establecido");
    }
    

    Esto debería recuperar correctamente el geopunto del usuario y construir un objeto GeoPoint a partir de él.

Comments are closed.