简体   繁体   中英

Flutter How to Save a Google Places Object Into Shared Preferences

How can I achieve the following functionality:

I'm attempting to save a PlacesDetailsResponse :

prefs.setString("last_known_google_places_location", json.encode(_placeDetail));
   

Then call it back like:

PlacesDetailsResponse last_location_obj = json.decode(prefs.getString("last_known_google_places_location")!);

Error:

E/flutter ( 5976): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'PlacesDetailsResponse?'
E/flutter ( 5976): #0      MyWidget.example(package:flutter_listings/main.dart:381:17)
E/flutter ( 5976): <asynchronous suspension>

I'm using the package:

import 'package:flutter_google_places/flutter_google_places.dart';

The code seems to suggest I can save it via json encode... here is the official class from the package:

@JsonSerializable()
class PlacesDetailsResponse extends GoogleResponseStatus {
  final PlaceDetails result;

  /// JSON html_attributions
  @JsonKey(defaultValue: <String>[])
  final List<String> htmlAttributions;

  PlacesDetailsResponse({
    required String status,
    String? errorMessage,
    required this.result,
    required this.htmlAttributions,
  }) : super(
          status: status,
          errorMessage: errorMessage,
        );

  factory PlacesDetailsResponse.fromJson(Map<String, dynamic> json) =>
      _$PlacesDetailsResponseFromJson(json);
  Map<String, dynamic> toJson() => _$PlacesDetailsResponseToJson(this);
}

It appears I was missing a step and not decoding the json into a PlacesDetailsResponse object, you can accomplish this via the class fromJson method:

 PlacesDetailsResponse the_last_place = PlacesDetailsResponse.fromJson(json.decode(prefs.getString("last_known_google_places_location")!));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM