Flutter Community
Published in

Flutter Community

Keep and Encrypt Data with Flutter

Do you ever think about how is it doing data on a phone? Let’s do encrypt any file or model together!

You have used the most important data like a specialdes spéciaux magazine pdf, you didn’t directly keep data on your phone because personperso access data without your application. This has big trouble anyone could take data in your phone so that share it for free.

What we do now 👀

  • Firstly we talk about crypto with flutter
  • Next, we’ll create a fileun fichier manager to keep data.
  • Later do encrypt and decrypt pdf file
  • Finally, keep encrypted pdf with your own model.

When you complete this operation, you can be going easily sleep. These steps enough for private data. If you want more powerful encryption, you have to need a server-side solution with your backend service.

Encryption Architecture

It is a too easy a scenario as just fetch data at cloud service after saving this data in phone directory with encrypt. These what important points to shouldn’t read data any third-party methods.

So let’s look at my plan:

  • We fetch data on service ( perhaps your backend service has encrypted data but my scenario only mobile device)
  • I write cache manager class by using a file. (read, delete etc)
  • I create an encryption manager and this manager read to the private key in the .env file.
  • Finally, I should call the cache manager in the main dart. It will remove cached data when the item date more than expires date.

While starting:

I’m using these packages for should create this architecture additionally using flutter last version with null safety.

Coding Time

I’m creating this service for this sample. This service returns the pdf URL with this model detail so keep cache data and pdf in the advance. While data caching on phone additionally should encrypt operation in data.

Firstly I create a cache service for backend operation.

Well, this layer has done additionally you need to network manager instance for every request. You should look at this core class.

I prepared a home view screen to show service data.

Now, I need to cache this pdf with modelmodèle detail. Perhaps you can use only pdf file encrypt but doesn't enough for your business as should make like library viewvue after showing every cached file in view.

I keep pdf in model json with this situation. I can show directly all item models.

Caching Operation

Firstly, I started to write a unit test easily. You got time, power and to develop code when you write testable code like an important operation. I created a mock file manager using testable code.

After I used this mock file instance and call in my custom scenario. Now open the file directory with the provider package then it can write any file in the phone directory.

These code work for download any pdf file and cache on the local path. It will save in your vscode folder.

Although doesn't forget, this folder path must add a .gitignore file as don't need this folder in the source.

When you need to mock a class for testing code, you should make this mock path provider class.

We knew how to cache pdf file ok then if we want to cache any dynamic model, we will make a JSON string to add cache. Caching model operationsopérations like pdf process but has a little different code. This different so that write bytesoctets changes to write string method.

That's it easy. We ready to use caching operation on the phone. We need to encrypt the algorithm with the use caching operation process. I choose the encrypt package and AES algorithm. This algorithm makes private data to the phone. Now, we’ll create encrypted data.

Firstly creating encrypt data class for using every operation. This class has two functionsfonctions to can crypt and decrypt process. AES algorithm work with Key and IV parameters. These parameters can be stored env file in the asset folder. (you can use this package to read data in the .env file)

Yes, it’s ready to use in every instance. These just need string source additionality to need Key & IV param. Any class calls this manager for can encryption own business. Time to go back to the test folder and getting the show crypto code.When without looking at the crypto code, it needs to create a key and iv string.

I was using this website and generated strong password with 32 and 16 size.

privateKey=zasdOyWOqczUffkizwypQadNLv2h4oA0
privateINV=xfpkDQJXIfb3mcnb

Page Design

And finally we readyprêt to use the app with the crypto and caching process. Let’s create an application so that we can use all process after fetch data from the backend(firebase).

Firstly create a view like this additionally write service code.

Future<void> _fetchAndShow() async { _changeLoading(); items = await homeService.fetchItem(); _changeLoading(); }

It will be fetch service and show the phone screen. We completed the home page so need the home detail page to show pdf data. Home detail page needs service param as service param send to download requestdemande and show pdf item view with pdf reader package.

I was using kartal package so i can navigate easy.

void navigateToDetail(int index) {
context.navigateToPage(HomeViewDetail(model:items[index],
homeService: homeService));
}

I prepare a sampleun échantillon view with to build method then show pdf view. We know the selected item so what we show in this widget as we send the previous screen.

Perhaps, you saw toBuild method for the first time. This power has come kartal package.

Well, we ready for all the core process. Time to come so we have to make an encrypted model and read this for can see it in detail.

Encrypt And Caching

We prepared the main steps for now. Let’s write encrypt operation in-app. I planed some features so I will add them to the end of the page.

We will see the power in testing so that we know all features. Now only write to app lifecycles.

I create IItemCache interface so that we take a power unit test both clean code.

I think, these functions what is mean understand basically for the name. Especially, the expiry value different so far. Well, we keep data but if we don’t add an expiration date, data always keep local and maybe this has a more size for the phone. The manager has checked cached data every app start and will check from now on to publish the date parameters.

Item model has needed two new parameters for pdf caching and shows data from the cached model.

Before started Item Model Cache must be created encrypt data instance;

The first methodméthode is cacheIt. It will be work caching with the encrypt manager.

This method creates a directory then normal pdf convert to an encrypted AES algorithm.

The next method is to get all data. This search data in the phone directory when the user calls the method. (like library view)

These functions open the directory after this check folder from _localpath. When the item directory is not empty, this function returns all data in decrypted format.

Next, the most important method is clearAllDatasWithExpiry. This method has worked every app start and checks validation with publish date.

This method checking your _expiryValue then if the method finds an item, it will be removed from the cache.

The last point is takeItemWithcache from id value. This method using dart collection class also without this package has an exception. (firstWhereOrNull)

import 'package:collection/collection.dart' as collection;

Well, cache manager and crypto manager class ready to views using.

Advanced Detail View and Library

Time to checking last operations and add initialize code. Firstly, I added a library view with tab view options. Library view working cached data list and clear every data in the phone.

Detail view fetches pdf data on service so this normally working. Now, I added cache checking and when the cache manager finds an item with id, it does not fetch again data to show view.

Other improvement code at home detail. I added cache controlcontrôle code with ItemCache interface so that if have the item, it will return my hand.

final cacheData = await _itemCache.takeItemWithCache(widget.model.id ?? 0);
if (cacheData != null) {
return cacheData.items;
}

The library view, it’s too simple. This class call cache data on init time then show it to the screen. Another ability of this class, it can clear all cache.

Another function is the clear cache process.

FloatingActionButton buildFloatingActionButtonDelete() 
=> FloatingActionButton(
onPressed: () async {
await itemCache.clearAllDatas();
setState(() {});
},
child: Icon(Icons.delete_forever));

Well, remove has done. We need to last code. I was said we have to clear data to expire date. I call this code in the main dart and check cache does has any expired item than now.

Oww everything has done 🥳

I added snackbar notification after cache completed. This show provide with global snackbarstate object:
final GlobalKey<ScaffoldMessengerState> scaffoldMassenger = GlobalKey();

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Veli Bacık

Veli Bacık

We always change the world, so just want it. Google Developer Expert Flutter & Dart, Gamer, Work More!