hive_cache 2.0.0 hive_cache: ^2.0.0 copied to clipboard
A persistent cache that uses hive.
import 'dart:convert';
import 'package:flutter/widgets.dart';
import 'package:hive_cache/hive_cache.dart';
import 'package:http/http.dart' as http;
import 'package:meta/meta.dart';
class Person implements Entity<Person> {
Person({
@required this.id,
@required this.firstName,
@required this.lastName,
}) : friends = Collection<Person>(
id: 'friends of $id',
fetcher: () async => json
.decode(await http.read('.../$id/friends'))
.map(Person.fromJson),
);
final Id<Person> id;
final String firstName;
final String lastName;
final Collection<Person> friends;
static Future<Person> fetch(Id<Person> id) async =>
Person.fromJson(json.decode(await http.read('.../$id')));
static Person fromJson(Map<String, dynamic> data) {
return Person(
id: Id<Person>(data['id']),
firstName: data['firstName'],
lastName: data['lastName'],
);
}
String toString() => '$firstName $lastName';
}
void main() async {
await HiveCache.initialize();
HiveCache
// The PersonAdapter will get generated by hive_generator.
// ignore: undefined_function
..registerEntityType(PersonAdapter(), Person.fetch);
// ...
// In some build method:
// ignore: return_of_invalid_type
return EntityBuilder<Person>(
id: Id<Person>('abc'),
builder: (context, snapshot, fetch) {
return Text(snapshot.data?.toString() ?? 'Loading…');
},
);
}