Seamless Reflect Widget Instantly in Flutter Using Hive Database: A Comprehensive Guide

Komal Thakkar
4 min readOct 3, 2023

--

Achieving Instant Like/Unlike Feed in Flutter with Hive

If you’re into making apps with Flutter, you know how important it is to keep everything running smoothly. Imagine it’s like a well-oiled machine. In this blog, we’re going to talk about a cool tool called Hive that helps keep your apps running smoothly by managing the information inside them. It is a really fast and easy-to-use database for Flutter apps. It’s kind of like a special tool that helps your apps remember and find information super quickly.

We’ll break it down step by step, so whether you’re new to this or already know a bit, you’ll be able to use Hive like a pro in your Flutter apps.

We’ll use this database to keep track of information and make sure it’s up to date on all our screens.

Let’s begin with a straightforward example of liking and unliking feed using a Hive database to make it easier to understand!.

I think you know a bit more than a complete beginner, so we don’t need to start with the basics of creating a project. Let’s move on to the next thing.

  • Add below plugin
#hive database
hive_flutter: ^1.1.0

Hive refers to a lightweight, fast, and efficient database. Hive is easy to work with and is optimized for local data storage, making it suitable for tasks like caching data or storing app settings.

I’ll be using a cubit here. I’ve previously covered this in detail in one of my earlier blog posts, so I won’t go into it again. Please refer to that post for a more in-depth explanation: cubit state management

  • I’m using static JSON data here. If you want to use live data, you’ll need to fetch it through an API. I’ve stored the feed list in a JSON file in the asset folder.
void getFeedList() async {
emit(FeedLoading());
String data = await rootBundle.loadString('assets/feed_list.json');

List? decodedData = jsonDecode(data);

List<FeedModel> feedList =
decodedData!.map((m) => FeedModel.fromJson(m)).toList();

emit(FeedListLoaded(feedList));
}
  • Now, let’s begin by initializing Hive and opening the box using a specific name.
Hive.init(directory.path);
await Hive.openBox(likeDB);
  • I’m going to make a like icon that can be used all over the app, so it shows whether you like or don’t like something.
ValueListenableBuilder(
valueListenable: likedList.listenable(),
builder: (context, dynamic value, Widget? child) {
},
);

A ValueListenable is an object that can be monitored for any alterations, and when it changes, it informs its observers.

ValueListenableBuilder is to refresh a specific part of your widget setup whenever the data inside the ValueListenable changes.

  • Now, I require the LikeService to handle Likes and Unlikes. This means that when a user likes a feed, you can add data to the database similar to the ‘like’ Map<String, dynamic>
    using Hive. When a user unlikes a feed, you should remove that feed’s ID data from the database.
Future addToLikedFeedList(FeedModel feedModel) async {
await likedList.put(feedModel.id, {
'id': feedModel.id,
'title': feedModel.title,
'name': feedModel.name,
'description': feedModel.description,
'urlToImage': feedModel.urlToImage,
'author': feedModel.author,
'content': feedModel.content,
'publishedAt': feedModel.publishedAt,
});
}
Future removeFromFeedLikeList(FeedModel feedModel) async {
await likedList.delete(feedModel.id);
}
  • Now, I have to display whether something has been liked or unliked by fetching the entire list from the database using this method.
final likedList = Hive.box(likeDB);
  • Now, we’ll send this data to the LikeIcon, which will display a filled heart icon if the ID matches the list’s ID, indicating that the feed is liked. If there’s no match, it will show an empty heart, indicating the feed is not liked.
GestureDetector(
child: likedList.keys.contains(feedModel!.id)
? const Icon(
Icons.favorite,
color: Colors.pink,
)
: const Icon(
Icons.favorite_border,
color: Colors.white,
),
onTap: () {
LikeService().handleLikeIconPressed(feedModel!, context);
},
),
  • Same with the LikeService, we check if the ID matches the list’s ID and then decide whether to like or unlike.
if (likedList.keys.contains(feedModel.id)) {
removeFromFeedLikeList(feedModel);
} else {
addToLikedFeedList(feedModel);
}
  • If you want to delete the list of liked items from Hive, just use this code.
Future clearLikedList() async {
await likedList.clear();
}
  • To retrieve all the liked items, you can use the code below. It fetches data like a Map<String, dynamic>, stores it in a model class, and displays it as a list of liked feeds.
final likedList = Hive.box(likeDB);
FeedModel feedModel = FeedModel(
id: likedList.getAt(index)['id'],
title: likedList.getAt(index)['title'],
description: likedList.getAt(index)['description'],
name: likedList.getAt(index)['name'],
urlToImage: likedList.getAt(index)['urlToImage'],
author: likedList.getAt(index)['author'],
);

Look at how easy it is to show data using the Hive database. It’s straightforward and can be used in various situations; just include a ValueListenableBuilder to update the view.

Thank you for taking the time to reach the end of this article. If you have any questions or need further clarification, please don’t hesitate to ask. You can find the complete code right here.

If you enjoyed the article, please give it a thumbs up to inspire me to write more content like this. Happy coding:)

--

--