Home > Mobile >  printing encoded map<String, dynamic> doesn't work flutter
printing encoded map<String, dynamic> doesn't work flutter

Time:08-02

I'm using geolocator package and I'm trying to save my position object locally using sharedpreferences, I have no problem with saving data and fetching it again my only problem is I can't encode my position object correctly, here's my code:

static Future setPosition(Position position) async {
    final unParsedPosition = jsonEncode(position);
    return await _preferences.setString(
      kPositionKey,
      unParsedPosition,
    );
  }
static Position? getPosition() {
    late final Position? parsedPosition;
    final unParsedPosition = _preferences.getString(
      kPositionKey,
    );
    if (unParsedPosition != null) {
      final positionJSON = jsonDecode(   <------ error here
        unParsedPosition,
      );
      parsedPosition = Position.fromMap(
        positionJSON,
      );
    }
    return parsedPosition;
  }

and this is the toJson() fun provided by geolocator package

Map<String, dynamic> toJson() => {
        'longitude': longitude,
        'latitude': latitude,
        'timestamp': timestamp?.millisecondsSinceEpoch,
        'accuracy': accuracy,
        'altitude': altitude,
        'floor': floor,
        'heading': heading,
        'speed': speed,
        'speed_accuracy': speedAccuracy,
        'is_mocked': isMocked,
      };

and my error happens when decoding I referenced it above in my getPosition fun

Unexpected character (at character 2)
{longitude: 31.3327177, latitude: 30.1449082, timestamp: 1659333183536, acc...
 ^

when I try to print

String s = jsonEncode(position);
print(s);

this doesn't work (my string not printed nothing happens), I need to know why thanks in advance

CodePudding user response:

I believe the toJson needs to return a string. The way you could do that is like this:

String toJson() => json.encode(toMap());

Map<String, dynamic> toMap() => {
    'longitude': longitude,
    'latitude': latitude,
    'timestamp': timestamp?.millisecondsSinceEpoch,
    'accuracy': accuracy,
    'altitude': altitude,
    'floor': floor,
    'heading': heading,
    'speed': speed,
    'speed_accuracy': speedAccuracy,
    'is_mocked': isMocked,
  };

CodePudding user response:

my code is working but the problem was that the stored data is not correct so trying to fetch it without updating it will give that error.

I stored it wrong but never update it and I keep fetching it without calling setPosition again, that's it

  • Related