开发者

Flutter save data from json with hive

I am trying to save api data with hive, and got this error:

HiveE开发者_StackOverflow社区rror: Cannot write, unknown type: User. Did you forget to register an adapter?

How can i save my data from api with Hive adapters and display them?

my code:

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


To save the objects in the hive, you first need to create an adapter. For example, if your User class has two properties name and age, your adapter will look like this:

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
}

Then run flutter pub run build_runner build.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜