flutter - 如何在 SharedPreferences 中存储对象?
问题描述
我有一个 BluetoothDevice 对象(flutter_blue)。它确实有一个 fromJson 函数,但同时缺少 toJson。当我尝试对其使用 toString() 时,它会产生以下输出:
{id: FF:FF:FF:FF:FF:FF, name: LazerDat, type: BluetoothDeviceType.le, isDiscoveringServices: false, _services: []}
然后,如果我尝试使用 toJson 将其解析为对象,则会出现此错误:
[ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: FormatException: Unexpected character (at character 2)
{id: FF:FF:FF:FF:FF:FF, name: LazerDat, type: Type.le, isDiscoveringService...
^
它试图找到引号,但 toString() 不会生成它们。如何在该字符串中添加引号?甚至可能吗?还有其他方法可以存储 BluetoothDevice 对象吗?
解决方案
使用jsonEncode
功能。
final bluetoothDevice = ...;
final encoded = jsonEncode(Bluetooth Device,
toEncodable: (device) {
// return `device` properties serialized
});
https://api.flutter.dev/flutter/dart-convert/jsonEncode.html
推荐阅读
- r - 将文本转换为数字?
- azure - Azure Site Recovery 保证 Azure 到 Azure 故障转移的恢复时间目标为两小时。对于任何类型的工作负载?
- jquery - 使用不带特殊字符 + 验证格式的日期输入创建一个 from
- python - 如果找到匹配,如何比较数据框中的两列并返回相应的记录?
- ios - 从 Swift 3 更新项目时的便利初始化错误
- azure-api-management - Azure API 管理在 API 终结点级别限制多个调用方 IP 地址 API
- android - 我正在开发用于跟踪用户活动的应用程序。我每隔 5 秒将他的 latlngs 存储到 db 中,稍后我想向用户展示他走过的路线
- java - 如何将 JAAS-J2C 身份验证数据从 Websphere 迁移到 Liberty
- javascript - 如何按分钟循环两个 DateTime?JavaScript
- javascript - 当 return new Promise((resolve, reject) => {}) 忘记调用resolve或reject时会发生什么?