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?
There are a few options:
Read and write files: https://flutter.io/reading-writing-files/
SQLite via a Flutter plugin: https://github.com/tekartik/sqflite
SQLCipher via a Flutter plugin: https://github.com/drydart/flutter_sqlcipher
SharedPreferences via a Flutter plugin: https://github.com/flutter/plugins/tree/master/packages/shared_preferences
Localstore via a Flutter plugin: https://pub.dev/packages/localstore
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
Storing key-value data on disk
but if you want to store large data you should go with SQLITE
How to get Started with SQLITE in Flutter
however you can always use firebase database which is available offline
how to add firebase to your flutter project
Firebase for Flutter Codelab from google
Since we are talking about local storage you can always read and write files to the disk
Reading and Writing Files
Other solutions :
Simple Embedded Application Store database
A Flutter plugin to store data in secure storage
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...
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.
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..
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.
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.
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
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');
}
There are a few options:
Moor: Persistence library for Dart
https://pub.dev/packages/moor_flutter
Read and Write file
https://flutter.io/reading-writing-files/
Shared preferences plugin for flutter
https://pub.dev/packages/shared_preferences
SQlite for flutter
https://pub.dev/packages/sqflite
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.
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
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)
Related
I am desperately trying to figure out how to initializeApp with Flutter (not React Native).
I know about the functions to use, but I can not find the firebaseConfig I need to pass into the function.
And no matter what I search for, every resources references to React Native, like as if nobody codes with Flutter since Firebase 9 has been released anymore (or I am the only dummy which is not able to resolve this by myself).
Can someone tell me where to get the firebaseConfig object from?
If I add a new app to my project, I only get the google-services.json, which does NOT include the firebaseConfig object I need to pass.
I understand your confusion now, let me explain. When the guy in the video talks about Firebase v9 he is talking about the SDK version which in the case of Javascript (which I suppose is his main topic in his channel) is currently 9.17.1 an the version 9 has been around since 2021 so it is not new. The different SDKs have their own versions for each platform so thinking it will be the same in every SDK is a mistake by itself. You can check the SDKS here. So there is no Firebase v9, there is a Firebase SDK for javascript version 9. They managed in that way in javascript and in flutter it is not the same. Being that the last update in the flutter SDK was literally yesterday I'm pretty sure they have their reasons to not implement the same functions in flutter since 2021.
Now, one of the thinks the guy talks in the video is deconstructing, which is something common in javascript. The way you do this in flutter is by using show.
So you would be doing this for example:
import 'package:cloud_firestore/cloud_firestore.dart' show FirebaseFirestore, QuerySnapshot; //Add everything you would be using
This way only the specific parts of the library will be imported and the amount of code the Dart VM has to load will be reduced.
As of the access to documents, it is still the same but you can easily create a helper class that contents your references to your collections and then just use that class to reduce the boilerplate code created by the firebase SDK.
You have to install the Firebase CLI and run firebase init.
You need to use the package firebase_core that will give you access to the class Firebase so you can use it to initialize your app Firebase.initializeApp() you can pass the default options for the current platform using Firebase.initilizeApp(options: DefaultFirebaseOptions.currentPlatform) usually your IDE will automatically import the corresponding package but in case it does not you would have to import 'firebase/firebase_options.dart';
An useful link to the documentation: Add Firebase to your Flutter App
I want to control cache data in graphql flutter.
for example, I want to set a time for deleting cache or...
I use graphql_flutter in my project and I know I can use FetchPolicy, but I want to access more in cache data.
https://pub.dev/packages/graphql_flutter
so can anyone help me please? how can I do that?
I want to get data from firebase to my flutter app. I created a collection at firebase but don't know how to use it on flutter. Already I've done the setup process between flutter and firebase and also added necessary dependencies. but now I need help to get data from firebase. collection name '0xethocity' ;
Here's the documentation, try to implement it by yourself. Let us know if you get stuck.
https://firebase.google.com/docs/flutter/setup?platform=ios
I'm developing a Flutter App, and one of the steps I need to take is to implement a way for user to increase/decrease the size of the text. For that, I'm thinking about making a slider in the settings page, which is quite straight-forward, but I don't know how to create a global value, change it (so it can't be a constant) and use it everywhere.
Any help is much is much appreciated !
You can store persistent data using shared_preferences or get_storage.
You can use the Hive framework to store the data locally on the device - https://docs.hivedb.dev/#/
First install Hive as a dependency and import it. Initialize Hive using Hive.initFlutter() (in the hive_flutter package).
Open a box using Hive.openBox("boxName"). Store the box as a variable - var box = Hive.box("boxName").
Add data into the box using box.put("key", "value").
Then you can access the data from anywhere you want by calling Hive.get("key").
I'm currently searching for a while how I can implement the following feature with Flutter for Android and IOS apps:
When the application is opened the first time after a version update I'd like to show a dialog with the information what's new in the new version / what has been fixed etc. - some kind of release notes.
I know various ways to show this dialog on application start; but how can I ensure that this is done only one time after the app version changed?
I was thinking about storing the various version messages as texts on the remote backend and give them an unique ID; via shared preferences or other persistance the last shown message ID could be stored and compared to the last available one.
But I see this feature in so many apps that I suppose there's a "standard way" to do this or maybe a package which supports this.
Kind regards
Michael
I don't know if there is a standard way of doing it, but here is a simple way to do it.
Include "package_info" plugin in your project.
import 'package:package_info/package_info.dart';
PackageInfo.fromPlatform().then((PackageInfo packageInfo) {
String runningVersion = packageInfo.version;
//compare runningVersion to the one saved in sharedPrefs
//if they don't match show the message
//then save runningVersion to sharedPrefs
});
by package_info package, you can figure out the current version of the application.
if the user updates the application by release centers(like google play), information stored in sharedPreference, remains. so you can save the application's version in sharedPreference and every time the app opens check the current version with info saved in sharedPreference if is the same no need for showing release note but if the current version is higher than the stored version, show release note and update sharePreference with the new version.
PackageInfo packageInfo = await PackageInfo.fromPlatform();
String currentVersion=packageInfo.version.toString();
SharedPreferences pref= await SharedPreferences.getInstance();
String latestAppVersion= pref.getString("latestAppVersion");
if(currentVersion.toInt()>latestAppVersion.toInt()){
//show release note
//update sharedPreferences with currentVersion
}