首页 > 解决方案 > Flutter Json 格式异常

问题描述

在我的应用程序中,我试图从共享首选项中检索数据并将该值传递给提供者。我怎么会遇到异常

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

获取值并将值传递给提供者的函数如下

   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);
}

json 数据以字符串形式存储在共享首选项中

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

我该如何解决这个问题?

标签: flutterflutter-providerflutter-sharedpreference

解决方案


您应该在 _localStorage.setValue 中使用 jsonEncode()。

在此处查看文档:https ://flutter.dev/docs/development/data-and-backend/json#serializing-json-manually-using-dartconvert


推荐阅读