Save decode json to hive box
- Dominant language
- Dart
- Stars
- 4.4k
- Forks
- 449
- PR merge metrics
- No merged PRs in 30d
Description
**Hi, I'm new in dart. I want save decode json in box =>
JSON like this:**
```json
{
"data": [
{
"id": 1,
"parent_id": 0,
"title": "Baby",
"price": 10,
"badges_count": 1873
},
{
"id": 2,
"parent_id": 0,
"title": "Health and Beauty",
"price": 10,
"badges_count": 1809
},
{
"id": 3,
"parent_id": 0,
"title": "Clothing",
"price": 10,
]
}
```
**I create model and generate adapter, init hive.box.**
My model:
```dart
@HiveType(typeId: HiveTypes.categories)
class Categories {
@HiveField(0)
int id;
@HiveField(1)
int parentID;
@HiveField(3)
String title;
@HiveField(4)
int price;
@HiveField(5)
int badgeCount;
Categories({
this.id = 0,
this.parentID = 0,
this.title = '',
this.price = 0,
this.badgeCount = 0
});
}
```
**And class helper for save it:**
```dart
class CategoriesDataHelper {
Box _categories;
//Save categories to Hive box
void saveCategories(Categories categories) {
_categories = Hive.box('categories_db');
_categories.put('categories', categories);
}
//Get categories from Hive box
Categories getCategories() {
_categories = Hive.box('categories_db');
return _categories.get('categories');
}
Future cacheCategories(dynamic categoriesData) async {
Categories categories;
categories = Categories(
id: categoriesData['id'],
parentID: categoriesData['parent_id'],
title: categoriesData['title'],
price: categoriesData['price'],
badgeCount: categoriesData['badges_count'],
);
saveCategories(categories);
}
Future clear() async {
await Hive.box('categories_db').clear();
}
}
```
**This method for save:**
```dart
/.../
var jsonResponse = convert.jsonDecode(resp.body);
var categories = jsonResponse['data'].toList();
CategoriesDataHelper().cacheCategories(categories);
```
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.