Wednesday, June 12, 2024
Google search engine
HomeCustom Shared Preferences In Flutter

Custom Shared Preferences In Flutter

Create your own Temporary/Persistent storage using plain dart

This article will walk you through the basics of file I/O and in the end, You will be able to build your own storage service just like shared preference using Dart: IO library.

For Complete Project Checkout :

flutter-devs/own-shared-preferences
A new Flutter project. This project is a starting point for a Flutter application. A few resources to get you started…github.com

Our main aim is to dig deep into Flutter file I/O so for that, we are creating our own shared preferences just to learn the basics of file I/O.


Shared preferences in flutter allow the developer to store some sort of state weather it’s related to user data like the day-night theme or some app-level data which we want to persist even after closing the app.

Let’s start by jumping straight into our Database Code for Complete Code along with UI checkout the above git repository.

import 'dart:io';
import 'dart:convert';
import 'package:path_provider/path_provider.dart';

class CoreDb {
//Creating singleton of CoreDb
CoreDb._();
static CoreDb _obj;
static instance() {
if (_obj == null) _obj = CoreDb._();
return _obj;
}

//Getting document path using path provider package
Future<String> get _localPath async {
final directory =
await getApplicationDocumentsDirectory();
return directory.path;
}

//getting instance of file using localPath
Future<File> get _localFile async {
final path = await _localPath;
return File('$path/preference.json');
}

//function to write data in file
void writeData(Map data) async {
File file = await _localFile;
Map<String, dynamic> tempMap;

if (await file.exists()) {
tempMap = json.decode(
file.readAsStringSync());
tempMap.addAll(data);
file.writeAsStringSync(json.encode(
tempMap));
} else {
file.writeAsStringSync(
json.encode(data));
}
}

//Function to get all the data in json format
Future<Map> getData({String key}) async {
File tempFile = await _localFile;
if (await tempFile.exists()) {
return json.decode(tempFile.readAsStringSync());
} else
return null;
}

//To delete data if exist in the file
Future deleteData(
String dataToDelete, Function onDelte, Function ifNotExist) async {
File tempFile = await _localFile;
if (!tempFile.existsSync()) {
ifNotExist();
} else {
Map data = json.decode(tempFile.readAsStringSync());
var result = data.remove(dataToDelete);
if (result == null) {
ifNotExist();
} else {
tempFile.writeAsStringSync(json.encode(data));
onDelte();
}
}
}
}

In the above code we are Interacting with files on our device using dart.io library the above code replicates the same functionality of shared Preferences.

Let’s take a look at each and every function one by one :

  1. localPath() : In localpath() we are accessing document directory using path provider package by calling getApplicationDocumentsDirectory(); method. This function returns a path of type string, we will be using this path for storing our Database file.
  2. localFile(): Now as we got our path from localPath() , We are now creating a file of type JSON using the path we got from localPath() and returning a File as an output return File(‘$path/preference.json’);
  3. writeData(): In this, we are first storing the file reference in a file variable File file = await _localFile; now we can access the same file, Now we create a temporary map and store the JSON file in it by parsing it using json.decode() tempMap = json.decode(file.readAsStringSync()); , After that, we add the new map to the tempMap variable using tempMap.addAll(data); now we right back the updated data by using json.Encode file.writeAsStringSync(json.encode(
     tempMap));
  4. getData(): This function returns a future Map if the file exist this function returns all the data present in the file by calling json.decode(tempFile.readAsStringSync()); .
  5. deleteData(): It takes three-parameter, Last two parameters (onDelete,ifNotExist) is called when the file got successfully deleted or when the file doesn’t exist. The first parameter takes a key of type string and removes that key-value pair if it exists using data.remove(dataToDelete); , This function (data.remove( )) returns null if the file dosent exist and returns the value if it exist .

Conclusion

In this article we learned how to do basic file I/O operations in flutter and alongside we also learned how to parse JSON file using dart: convert library and accessing the device storage using path_provider package. Now go on and create your own file storage system or customize it as per your need ,Sky is the limit 🙃🙃🙃.

Check out the working prototype at:

flutter-devs/own-shared-preferences
A new Flutter project. This project is a starting point for a Flutter application. A few resources to get you started…github.com

Thanks for reading this article.

If you find it interesting Please Clap! and if you found anything wrong please let me know I would appreciate it for your contribution.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments