Sometimes your local database contains a huge amount of data and you just need to deal with it. Such read-heavy applications lead to significant slow down, screen freezing and other nightmare scenarios. Simple applications with GUI work mostly on a single thread, knowns as the ”main” thread, but when the app grows, more and more tasks need to be processed. That usually forces developers to move some methods onto a different thread – just like when an application has to work with heavy computations, e.g. processing queries in huge databases.In this article, I will demonstrate how to avoid screen freezing of read-heavy apps in Flutter using the Drift framework. The method allows to manage large databases without compromizing the performance, especially in UI. Let’s see how it’s done in three simple steps.
Step 1: Enable DriftIsolate
To work with threads, Flutter uses a class named Isolate. In Drift, there is a special class named DriftIsolate, which makes the transfer of your database onto another thread much easier.
Let’s start by enabling this feature. Create a file named build.yaml in your project root directory (not in lib\ folder!). Include the below code:
After that, run the build with build_runner to generate a new constructor for your database class, which will allow allow you to open the database in another thread:
Step 2: Open the database in another Isolate
When your database class is ready, the next step is to open it on another Isolate:
In the _backgroundConnection method, the first two lines will create your in-memory database and then create a connection between that database and the executor. But, dealing with an existing database in a file using background isolate is more difficult. I will show how to simplify it in the following section.
Step 3: Initialize with path_provider
Currently Flutter’s path_provider is not available for use on background Isolates. Some methods for providing the path (e.g. getLibraryDirectory() ) have to be called on the main thread. To solve this problem you can calculate the path first, then send it to DriftIsolate:
By using DatabaseConnection.delayed() asynchronous initialization of database can be done synchronously.
We’re done here!
After implementing this solution, you will notice that your app will work much faster while it processes database queries. It also resolves the screen freeze problem, because all heavy computation is away from the main thread. Let me know if this article was helpful for you.