Flutter - Saving Files

5,509

Solution 1

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

Solution 2

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:

Share:
5,509
Jakob
Author by

Jakob

Updated on December 04, 2022

Comments

  • Jakob
    Jakob 11 months

    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

    • How do I save an object?
    • Can I simply save a list of objects?
    • If I have two different Objects do I save them on one or two separate files? Same with theme or preference values the user chooses?
    • In my App, the user should be able to extend an existing list of objects. How do I save those already existing Objects to the device?
      • How do I read the files and how will the data be structured? Do I get the objects i saved or just their values?

    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!

    • Raouf Rahiche
      Raouf Rahiche over 5 years
      you should start from here
    • grepLines
      grepLines over 5 years
      Try cloud_firestore flutter package if you want to store data in a structured way.
  • Jakob
    Jakob over 5 years
    Okay, thank you very much, this already seems pretty helpful! But what are small amounts of data? Can/Should i save a List of 100+ Objects with shared preferences?
  • Richard Heap
    Richard Heap over 5 years
    A few hundred items
  • Jakob
    Jakob over 5 years
    So a few hundred objects? Or is an object with ten int values ten items? Sorry for asking so many questions^^
  • Richard Heap
    Richard Heap over 5 years
    Apparently there's a limit on Android of 1.4MB, with no limit on iOS, so as long as your json is less than that you'll be OK. I.E. it'll handle lists of a few hundred objects.
  • Richard Heap
    Richard Heap over 5 years
    @Jakob Did you get this working? If so, it's nice to upvote and/or accept the answer that helped you - which helps build reputation all round :-)
  • Jakob
    Jakob over 5 years
    Yes, your answer was very helpful, tho I'm thinking of using firebase for my big project!