155

In Android, If I have the information I want to persist across sessions I know I can use SharedPreferences or create a SQLite database or even write a file to the device and read it in later.

Is there a way to save and restore data like this just using Flutter? Or would I need to write device-specific code for Android and iOS like in the services example?

ankushlokhande
  • 870
  • 5
  • 20
Reagankm
  • 4,780
  • 9
  • 27
  • 52

10 Answers10

166

There are a few options:

chuyentt
  • 33
  • 1
  • 4
Seth Ladd
  • 112,095
  • 66
  • 196
  • 279
95

If you are in a situation where you wanna save a small value that you wanna refer later, then you should store your data as key-value data using shared_preferences

but if you want to store large data you should go with SQLITE

however you can always use firebase database which is available offline

Since we are talking about local storage you can always read and write files to the disk

Other solutions :

danronmoon
  • 3,814
  • 5
  • 34
  • 56
Raouf Rahiche
  • 28,948
  • 10
  • 85
  • 77
  • 1
    how to decide when to use sqflite or firebase? – stuckedunderflow Dec 07 '18 at 08:25
  • 1
    `sqflite` stores it only in the phone. `firebase` gets sync'ed in a central database where you can perform queries in your backend. `firebase` also makes easy synchronization between devices. – Feu Dec 15 '18 at 18:08
  • Please note that Firebase's Firestore defaults to 10MB and may be set to no less than 1MB and a max of 100MB. Pure offline access is not recommended. If you plan to use this as a local storage option only and the data is large, you may need to reconsider. https://firebase.google.com/docs/reference/android/com/google/firebase/database/FirebaseDatabase#setPersistenceCacheSizeBytes(long) – astone26 Dec 31 '18 at 15:44
  • 1
    This should be preferred answer, because it simply explains where to look in different scenarios. – janpeterka May 12 '20 at 08:31
27

A late answer but I hope it will help anyone visiting here later too..

I will provide categories to save and their respective best methods...

  1. Shared Preferences Use this when storing simple values on storage e.g Color theme, app language, last scroll position(in reading apps).. these are simple settings that you would want to persist when the app restarts.. You could, however, use this to store large things(Lists, Maps, Images) but that would require serialization and deserialization.. To learn more on this deserialization and serialization go here.
  2. Files This helps a lot when you have data that is defined more by you for example log files, image files and maybe you want to export csv files.. I heard that this type of persistence can be washed by storage cleaners once disk runs out of space.. Am not sure as i have never seen it.. This also can store almost anything but with the help of serialization and deserialization..
  3. Saving to a database This is enormously helpful in data which is a bit complex. And I think this doesn't get washed up by disc cleaners as it is stored in AppData(for android).. In this, your data is stored in an SQLite database. Its plugin is SQFLite. Kinds of data that you might wanna put in here are like everything that can be represented by a database.
emanuel sanga
  • 815
  • 13
  • 17
15

You can use shared preferences from flutter's official plugins. https://github.com/flutter/plugins/tree/master/packages/shared_preferences

It uses Shared Preferences for Android, NSUserDefaults for iOS.

Furkan Tektas
  • 309
  • 3
  • 6
  • 1
    Is this ideal for large databases? – temp_ May 10 '18 at 17:38
  • 1
    @temp_ I don't know much about iOS. Shared Preferences on Android, however, are definitively not suited for large database. They are written as plain xml files to the file system, and read from file system if requested. They are mainly used for storing app preferences and similar things. – forgemo May 10 '18 at 21:58
  • This seems to work better for Shared Preferences: https://pub.dev/packages/shared_preferences – Yster Sep 24 '19 at 17:34
14

You can use Localstorage

flutter pub add localstorage

1- Add dependency to pubspec.yaml (Change the version based on the last)

dependencies:
  ...
  localstorage: ^4.0.0+1

2- Then run the following command

flutter packages get

3- import the localstorage :

import 'package:localstorage/localstorage.dart';

4- create an instance

class MainApp extends StatelessWidget {
  final LocalStorage storage = new LocalStorage('localstorage_app');
  ...
}

Add item to lcoalstorage :

void addItemsToLocalStorage() {
  storage.setItem('name', 'Abolfazl');
  storage.setItem('family', 'Roshanzamir');

  final info = json.encode({'name': 'Darush', 'family': 'Roshanzami'});
  storage.setItem('info', info);
}

Get an item from lcoalstorage:

void getitemFromLocalStorage() {
  final name = storage.getItem('name'); // Abolfazl
  final family = storage.getItem('family'); // Roshanzamir
  
  Map<String, dynamic> info = json.decode(storage.getItem('info'));
  final info_name=info['name'];
  final info_family=info['family'];
}

Delete an item from localstorage :

void removeItemFromLocalStorage() {
  storage.deleteItem('name');
  storage.deleteItem('family');
  storage.deleteItem('info');
}
Abolfazl Roshanzamir
  • 12,730
  • 5
  • 63
  • 79
  • 1
    I haven't tried this library, but seems like this is a way to store files in JSON with unique key. This looks a bit like NoSQL, but it's lack of all the DB operations such as query and update. that's the difference compare with sqllite. – Jason Ching Mar 27 '22 at 17:31
  • How to list view all the items which saved in the json file? – user1267779 Sep 07 '22 at 21:28
13

If you need to store just simple values like API token or login data (not passwords!), here is what I used:

import 'package:shared_preferences/shared_preferences.dart';

asyncFunc() async { // Async func to handle Futures easier; or use Future.then
  SharedPreferences prefs = await SharedPreferences.getInstance();
}
...

// Set
prefs.setString('apiToken', token);

// Get
String token = prefs.getString('apiToken');

// Remove
prefs.remove('apiToken');

Don't forget to add shared_preferences dependency in your pubspec.yaml (preserve spacing format):

dependencies:

  shared_preferences: any
Rap
  • 6,851
  • 3
  • 50
  • 88
George Zvonov
  • 9,401
  • 5
  • 33
  • 37
8

There are a few options:

Moor: Persistence library for Dart

Read and Write file

Shared preferences plugin for flutter

SQlite for flutter

Community
  • 1
  • 1
Atul
  • 1,477
  • 12
  • 9
  • 1
    Moor is still experimental on Web. You can't write files on Web. Shared preferences does not guarantee writes. SQlite only supports mobile. None of these are cross platform options. – Richard May 27 '22 at 13:28
4

I was looking for the same, simple local storage but also with a reasonable level of security. The two solutions I've found that make the most sense are flutter_secure_storage (as mentioned by Raouf) for the small stuff, and hive for larger datasets.

therightstuff
  • 833
  • 1
  • 16
  • 21
2

I think If you are going to store large amount of data in local storage you can use sqflite library. It is very easy to setup and I have personally used for some test project and it works fine.

https://github.com/tekartik/sqflite This a tutorial - https://proandroiddev.com/flutter-bookshelf-app-part-2-personal-notes-and-database-integration-a3b47a84c57

If you want to store data in cloud you can use firebase. It is solid service provide by google.

https://firebase.google.com/docs/flutter/setup

Ishan Fernando
  • 2,758
  • 1
  • 31
  • 38
2

Hive (https://pub.dev/packages/hive) is very fast and flexible solution. But if you have experience with SQL; you can use SqfLite packages (https://pub.dev/packages/sqflite)