用Flutter Hive从json中保存数据



我正在尝试用hive保存api数据,并得到此错误:

HiveError: Cannot write, unknown type: User。你忘记注册适配器了吗?

我如何保存我的数据从api与Hive适配器和显示它们?

我代码:

static Future<User> getUser() async {
var url = '${Constants.API_URL_DOMAIN}action=user_profile&token=${Constants.USER_TOKEN}';
print(Constants.USER_TOKEN);
final response = await http.get(Uri.parse(url));
final body = jsonDecode(response.body);
var box = Hive.box('myBox');
box.put('user', User.fromJson(body['data']));
return User.fromJson(body['data']);
}

有两种方法可以使用Flutter Hive数据库。

  1. 将原始数据(如List, Map, DateTime, BigInt等)直接保存到Hive Box
  2. 使用Hive类型适配器的非原始数据。(查看更多信息)

您正在尝试保存User类对象,它不是原始类型,因此您将不得不使用Hive Type Adapters

如果你不想使用类型适配器,那么你可以直接保存你从API调用中获得的json数据,修改后的代码将看起来像这样。

static Future<User> getUser() async {
var url = '${Constants.API_URL_DOMAIN}action=user_profile&token=${Constants.USER_TOKEN}';
print(Constants.USER_TOKEN);
final response = await http.get(Uri.parse(url));
final body = jsonDecode(response.body);
var box = Hive.box('myBox');
box.put('user', body['data']);
return User.fromJson(body['data']);
}

要在hive中保存对象,首先需要创建一个适配器。例如,如果您的User类有两个属性nameage,您的适配器将看起来像这样:

part 'user.g.dart';
@HiveType(typeId: 0)
class User{
@HiveField(0)
final String title;
@HiveField(1)
final int age;
User({this.title, this.age});
// other methods: fromJson, toJson
}

然后运行flutter pub run build_runner build

之后,在main()函数中。不要忘记注册适配器,并在需要时打开盒子。如:

void main() async {
await Hive.initFlutter();
Hive
..registerAdapter(UserAdapter());
await Hive.openBox<User>('usersbox');
}

最新更新