首页 > 解决方案 > 如何在 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 对象吗?

标签: flutterdart

解决方案


使用jsonEncode功能。

final bluetoothDevice = ...;
final encoded = jsonEncode(Bluetooth Device, 
         toEncodable: (device) {
            // return `device` properties serialized
          });

https://api.flutter.dev/flutter/dart-convert/jsonEncode.html


推荐阅读