This is the first day of my participation in the Gwen Challenge in November. Check out the details: the last Gwen Challenge in 2021
Persistent data storage in Flutter is an indispensable function. This article mainly introduces several persistent stores in Flutter:
shared_preferences
Android, based on SharePreferences; IOS is developed based on NSUserDefaults for simple key-value storage
- The introduction of
Dependencies: shared_preferences: ^ mid-atlantic movedCopy the code
- Basic usage:
class LocalStorage { static SharedPreferences? prefs; static initSP() async { prefs = await SharedPreferences.getInstance(); } static save(String key, String value) { prefs? .setString(key, value); } static get(String key) { return prefs? .get(key); } static remove(String key) { prefs? .remove(key); }}Copy the code
path_provider
File storage
- The introduction of
Dependencies: path_provider: ^ 2.0.7Copy the code
- Basic introduction
-
Get the application cache directory: getTemporaryDirectory
- Similar to iOS NSTemporaryDirectory and Android getCacheDir
- / data/user / 0 / package/cache
-
Access application file directory: getApplicationDocumentsDirectory
- Similar to NSDocumentDirectory on iOS and AppData directory on Android
- When an application is deleted, the system clears the directory
- / data/user / 0 / package/app_flutter
-
Memory card: external.getexternalstoragedirectory
- Only The Android platform is supported
- / storage/emulated / 0 / Android/data/files/package name
- Basic usage
/ / / to get the store path Future < String > getTemporaryDirectoryString () is async {final directory = await getTemporaryDirectory (); return directory.path; } Future<String> getApplicationDocumentsDirectoryString()async{ final directory = await getApplicationDocumentsDirectory(); return directory.path; } Future<String> getExternalStorageDirectoryString()async{ final directory = await getExternalStorageDirectory(); return directory? .path ?? ""; } / / to create references to the Future of File location < File > get _localFile async {final path = await getApplicationDocumentsDirectoryString (); return new File('$path/counter.txt'); Future<File> writeCounter(int counter) async {final File = await _localFile; // Write the file return file.writeAsString('$counter'); Future<int> readCounter() async {try {final file = await _localFile; // Read the file String contents = await file.readAsString(); return int.parse(contents); } catch (e) { // If we encounter an error, return 0 return 0; }}Copy the code
Sqflite database
- The introduction of
Dependencies: sqflite: ^ 2.0.0 + 4Copy the code
2. Basic introduction
- Execute the SQ statement to create the table
- Provides a method for retrieving a Transaction
- Execute the add, delete, change query SQ statement using Transaction
- The basic use
Class MainDatabaseManager {// Factory mode Factory MainDatabaseManager() => _getInstance(); static MainDatabaseManager get instance => _getInstance(); static MainDatabaseManager? _instance; static Database? tkDatabase; static List<String> _nameList = []; MainDatabaseManager._internal() {// initialize} static MainDatabaseManager _getInstance() {if (_instance == null) { _instance = new MainDatabaseManager._internal(); } _instance! ._createTable(); return _instance! ; } /// initialize database initDB() {_createTable(); _createTable() async {var databasePath = await getDatabasesPath(); String path = join(databasePath, "tkDataBase.db"); TkDatabase = await openDatabase(path, version: 1, onCreate: (Database db, Int version) async {/// Create table await db.execute("create table if not EXISTS TK_Main_Data (ID INTEGER not NULL PRIMARY KEY AUTOINCREMENT,name TEXT UNIQUE,data BLOB)"); }); CommitTransaction (Function(Transaction TXN) Action) async {try {await tkDatabase? .transaction((txn) async { Batch batch = txn.batch(); await action(txn); await batch.commit(noResult: true, continueOnError: true); }); } catch (e) { print('--- transaction failed -----'); -parameter name: indicates the name of the data to be saved. -parameter data: indicates the data to be saved. -parameter type: indicates the data to be saved. Type */ _saveDataWith(String name, bool containsMember, String data, Transaction txn) async { String dataName = name + (containsMember ? UserStore().getMemberId() : ""); int id = await txn.rawInsert( 'INSERT or replace INTO TK_Main_Data(name,data) VALUES(? ,?) ', [dataName, data]); print('inserted2:$id'); } // updateData(String name, bool containsMember, dynamic data, Transaction txn) async { dynamic result = await selectData(name, containsMember, txn); if (result == null || result == "") { _nameList.add(name); } _saveDataWith(name, containsMember, data, txn); } /* Query data. -parameter name: specifies the name of the data to be queried. -parameter type: specifies the type. */ Future<dynamic> selectData(String name, bool containsMember, Transaction txn) async { String dataName = name + (containsMember ? UserStore().getMemberId() : ""); // query dynamic result = await txn. rawQuery("select data from TK_Main_Data where name = '$dataName'"); if (result ! = null && result is List && result.length > 0) { return result.first["data"] ?? ""; } return ""; } / / / log out, delete the related to the current user cache deleteAllDataForMember (Transaction TXN) async {the if (UserStore. Instance. GetMemberId ()! = "") { for (String name in _nameList) { String dataName = name + UserStore.instance.getMemberId(); Txn.execute ("delete from TK_Main_Data where name = (?)) ", [dataName]); } _nameList = []; } } onDisposed() { tkDatabase? .close(); }}Copy the code