Home > Back-end >  How to add json object to hive flutter?
How to add json object to hive flutter?

Time:07-10

I have the next problem: add my data to the hive flutter my data is following:

Author_1, links, (articles_1, articles_2, ..., articles_N),
Author_2, links, (articles_1, articles_2, ..., articles_N)
Author_3, links, (articles_1, articles_2, ..., articles_N)

That is, all my data consists of the name of the authors, links and articles. But each author has more than one article and therefore I had a problem and I don’t understand how to implement it in the hive flutter, please tell me

CodePudding user response:

do You know how save model into hive? if no, enter link description here if yes, so with register your model to hive, hive knows your model as data type that you can save objects like that, now that's how I understand it, your model consist of String author, String link, List<String> article, so build this is model and after register to hive, save your model objects into that

@HiveType(typeId: 0)
class Paper {
  Paper({
    this.author,
    this.link,
    this.articles,
  });

  @HiveField(0)
  final String? author;
  @HiveField(1)
  final String? link;
  @HiveField(2)
  final String? articles;

  factory Paper.fromJson(Map<String, dynamic> json) => Paper(author: json['author'], link:json['link'], articles:json['articles'])
  
}

class PaperAdapter extends TypeAdapter<Paper> {
  @override
  int get typeId => 0;

  @override
  Paper read(BinaryReader reader) {
    int numOfFields = reader.readByte();
    Map fields = <int, dynamic>{
      for (int i = 0; i < numOfFields; i  ) reader.readByte(): reader.read(),
    };

    return Paper(
      author: fields[0],
      link: fields[1],
      articles: fields[2],
    );
  }

  @override
  void write(BinaryWriter writer, Paper obj) {
    writer
      ..writeByte(3)
      ..writeByte(0)
      ..write(obj.author)
      ..writeByte(1)
      ..write(obj.link)
      ..writeByte(2)
      ..write(obj.articles);
  }
}

after that Hive.registerAdapter(PaperAdapter()); then easily var box = await Hive.openBox<Paper>('paperBox'); box.add(Paper(author:'a', link:'b', articles:['aa', 'bb']));

  • Related