Home > Back-end >  Json decode Instance of Item
Json decode Instance of Item

Time:05-14

I'm trying to save a list of object into a shared preference for easy storage. I'm getting the error [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: FormatException: Unexpected character (at character 1) -> E/flutter ( 7980): Instance of 'History'

Method

Future<void> recordLocation(lat, long) async {
  List<History> histories = [];
  final prefs = await SharedPreferences.getInstance();

  //fetching history
  if (prefs.getStringList('history') != null) {
    List<String>? prevHistory = prefs.getStringList('history');
    histories = prevHistory!
        .map<History>((i) => History.fromJson(json.decode(i)))
        .toList();
  }

  //setting history
  History current = History(lat.toString(), long.toString());
  histories.add(current);
  List<String> newHistory = histories.map((i) => i.toString()).toList();
  await prefs.setStringList('history', newHistory);
}

History model

class History {
  String? latitude;
  String? longtitude;

  History(this.latitude, this.longtitude);

  History.fromJson(Map<String, dynamic> json) {
    latitude = json['latitude'];
    longtitude = json['longtitude'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['latitude'] = this.latitude;
    data['longtitude'] = this.longtitude;
    return data;
  }
}

CodePudding user response:

People usually declare the fromJson method as a factory method and data classes as immutable. Try this instead:

class History {
  final String latitude;
  final String longtitude;
    
  const History({
    this.latitude = '', 
    this.longtitude = '',
  });
    
  factory History.fromJson(Map<String, dynamic> json) => 
    History(
      latitude: json['latitude'] as String? ?? '',
      longtitude: json['longtitude'] as String? ?? '',
    );

  Map<String, dynamic> toJson() => {
    'latitude': latitude,
    'longtitude': longtitude,
  };
}

CodePudding user response:

Edit:

import 'dart:convert';

class History {
  String? latitude;
  String? longtitude;

  History(this.latitude, this.longtitude);

  History.fromJson(Map<String, dynamic> json) {
    latitude = json['latitude'].toString();
    longtitude = json['longtitude'].toString();
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['latitude'] = this.latitude;
    data['longtitude'] = this.longtitude;
    return data;
  }

  @override
  String toString() {
    String res = '{"latitude":${latitude ?? ""},"longtitude":${longtitude ?? ""}}';
    return res;
  }
}

void main(){
  
  List<History> histories = [];
  List<String>? prevHistory = [];
  for(int i=0;i<10;i  ){
    History his = History(i.toString(), i.toString());
    prevHistory!.add(his.toString());
  }
  
  if(prevHistory != null){
    histories = prevHistory!.map<History>((i){
      return History.fromJson(jsonDecode(i));
    }).toList();
  }
  
  for(int i=0;i<histories.length;i  ){
    print(histories[i].toString());
  }
  
}

I have run this code in dartpad and it gives the output as:

{"latitude":0,"longtitude":0}
{"latitude":1,"longtitude":1}
{"latitude":2,"longtitude":2}
{"latitude":3,"longtitude":3}
{"latitude":4,"longtitude":4}
{"latitude":5,"longtitude":5}
{"latitude":6,"longtitude":6}
{"latitude":7,"longtitude":7}
{"latitude":8,"longtitude":8}
{"latitude":9,"longtitude":9}

The problem was with the conversion of string to Map<String, dynamic>

Edit 2:

Here if you do not want to change your history class then just make edit in the toString() method:

  String toString() {
    String res = '{"latitude":"${latitude ?? ""}","longtitude":"${longtitude ?? ""}"}';
    return res;
  }
  • Related