Home > Net >  Flutter Json FormatException
Flutter Json FormatException

Time:09-17

In my application, i'm trying to retrieve the data from shared preferences and pass that value to the provider. How ever im getting a exception

FormatException (FormatException: Unexpected character (at character 2)
{token: eyJh...
 ^  

The function to get and pass the value to provider is as follows

   Future<void> insertUsertolocal() async {
        final storage = new LocalStorage();
        final _user = await storage.getValue(Constants.USER); // retrieves data from key
        User user = User.fromJson(jsonDecode(_user)); // receives FortmatException
        print(user.email);
}

The json data is stored in shared preferences as string

_localStorage.setValue(Constants.USER, user.toString());

How can i resolve this issue??

CodePudding user response:

You should use jsonEncode() in _localStorage.setValue.

Check the doc here: https://flutter.dev/docs/development/data-and-backend/json#serializing-json-manually-using-dartconvert

  • Related