Reputation: 23
I am currently learning flutter and dart. I am not a very experienced developer (mainly some C++ knowledge), but I really like Flutter and I started to develop some Apps for testing and learning. The only real problem I have is that I don't understand how to save stuff to the device. I know there are some tutorials out there but they don't really cover what I want to know.
The Counter Example is nice to show a beginner how to save one int. But in my App, I want to save a list of objects with int, string, and list values.
So my questions are
You see: I am not very experienced yet, but I really want to learn more about Flutter! So if you have any good links or advice regarding that subject or generally Flutter please share them!
Thank you for your help!
Upvotes: 2
Views: 6602
Reputation: 1547
Saving objects means saving state of app. It can be done by data saving techniques like database or sharedpreference
If you need to save exact object at that time it could be hectic to use sharedPreference or sqflite.
But it is lot easier if you use HIVE Database for flutter.
References you can follow:
https://resocoder.com/2019/09/30/hive-flutter-tutorial-lightweight-fast-database/
Upvotes: 1
Reputation: 51750
When I need to store small amounts of data, I use shared_preferences. I encode the Dart objects into json before storing and decode on retrieval.
To save an object, encode it to json. To save a List of objects, encode the whole list. You can choose whether to save unlike objects together or separately.
When the list of objects saved changes I simply re-write the whole list.
You should probably start with some simple objects. That way you will find that you can save and read them back pretty easily.
(One of the great things about Dart is that you can run it from the command line. This way you can create and test your data objects first before even including them in a Flutter app. Unit testing is built right into Dart.)
Here's an example of a class that knows how to encode/decode itself as json
class Membership {
int _index;
String _name;
String _id;
Membership(this._index, this._name, this._id);
Membership.fromJson(Map<String, dynamic> m) {
_index = m['index'];
_name = m['name'];
_id = m['id'];
}
String get id => _id;
String get name => _name;
int get index => _index;
Map<String, dynamic> toJson() => {
'index': _index,
'name': _name,
'id': _id,
};
}
If you have a List of memberships you persist it like this
List<Membership> memberships = [];
final String membershipKey = 'someuniquestring'; // maybe use your domain + appname
SharedPreferences sp = await SharedPreferences.getInstance();
sp.setString(membershipKey, json.encode(memberships));
and retrieve it like this
memberships = [];
json
.decode(sp.getString(membershipKey))
.forEach((map) => memberships.add(new Membership.fromJson(map)));
// don't forget to call setState((){}) to update the Widgets
Upvotes: 3