Parth Patel
Parth Patel

Reputation: 115

How To Store List in Hive? - Flutter

I am building an application for experience. I am trying to store list in hive. So, can anyone explain how can I store list in hive?

In below list, all data are stored. I want to store these data in hive through all category list.

List<CategoryModel> allcategorylist =[]

Upvotes: 3

Views: 8741

Answers (2)

Hadiuzzaman
Hadiuzzaman

Reputation: 464

First of all, you need to modify your CategoryModel class like this-

part 'category_model.g.dart';

@HiveType(typeId: 0, adapterName: "CategoryAdapter")
class CategoryModel{

  @HiveField(0)
  final String exampleField1; 

  @HiveField(1)
  final String exampleField2;

  CategoryModel({required this.exampleField1, required this.exampleField2});
}

After that , make sure you added those dependencies in your pubspec.yaml file

dependencies:
  hive: ^2.2.3
  hive_flutter: ^1.1.0


dev_dependencies:
  hive_generator: ^2.0.1
  build_runner: ^[latest version]

Now run this command in your terminal

flutter packages pub run build_runner watch --delete-conflicting-outputs

After successfully run this command hive_generator create a adapter named CategoryAdapter, you will find this class in category_model.g.dart file.

Now modify your main.dart file like this

  void main() async {

  WidgetsFlutterBinding.ensureInitialized();
  await Hive.initFlutter();
  Hive.registerAdapter(WallpaperAdapter());

  runApp(MyApp());
  }

Now your configuration is ready for store the custom object

Store CategoryModel object:

  const key = 'categoryKey';
  final box = await Hive.openBox<List>('categoryList');

  final newCategory = CategoryModel(
    exampleField1: "This is example field1", 
    exampleField2: "This is example field2",

  );

  List<CategoryModel> categoryList = [];
 
  categoryList.add(newCategory);

  await box.put(key, notificationList);

Fetch data:

  final categoryList = box.get(key, defaultValue: []) ?? [];
  print(categoryList);

Upvotes: 4

Usama Karim
Usama Karim

Reputation: 1428

Have you gone through the documentation?

Here is an example from the documentation.

import 'package:hive/hive.dart';

void main() async {
  var box = await Hive.openBox('someBox');

  var initialList = ['a', 'b', 'c'];
  box.put('myList', initialList);

  var myList = box.get('myList');
  myList[0] = 'd';

  print(initialList[0]); // d
}

Upvotes: 3

Related Questions