Created
November 19, 2023 09:49
-
-
Save JavascriptMick/b4e948cd1bf9feb40e850e1f37b37a67 to your computer and use it in GitHub Desktop.
Flutter - Persistent storage of a list of custom objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:shared_preferences/shared_preferences.dart'; | |
import 'dart:convert'; | |
class PersistentStorageService { | |
static Future<List<MyObject>> getMyObjects() async { | |
SharedPreferences prefs = await SharedPreferences.getInstance(); | |
List<String> jsonStringList = prefs.getStringList('my_objects') ?? []; | |
return [ | |
for (var jsonString in jsonStringList) | |
MyObject.fromJson(jsonDecode(jsonString)) | |
]; | |
} | |
static saveMyObjects(List<MyObject> myObjects) async { | |
SharedPreferences prefs = await SharedPreferences.getInstance(); | |
await prefs.setStringList( | |
'my_objects', [for (var myo in myObjects) jsonEncode(myo.toJson())]); | |
} | |
} | |
class MyObject { | |
final DateTime aDate; | |
final List<String> someStrings; | |
MyObject({required this.aDate, required this.someStrings}); | |
// Convert a MyObject object into a map | |
Map<String, dynamic> toJson() { | |
return { | |
'aDate': aDate.toIso8601String(), | |
'someStrings': someStrings, | |
}; | |
} | |
// Create a MyObject object from a map | |
static MyObject fromJson(Map<String, dynamic> json) { | |
return MyObject( | |
aDate: DateTime.parse(json['aDate']), | |
someStrings: List<String>.from(json['someStrings']), | |
); | |
} | |
} | |
Future<void> usage() async { | |
List<MyObject> myObjects = await PersistentStorageService.getMyObjects(); | |
myObjects.add( | |
MyObject(aDate: DateTime.now(), someStrings: ['Dart', 'is', 'Fun!'])); | |
await PersistentStorageService.saveMyObjects(myObjects); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
environment: | |
sdk: ">=3.1.5 <4.0.0" | |
dependencies: | |
flutter: | |
sdk: flutter | |
shared_preferences: ^2.2.2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment