0

For my Flutter app I'm trying to access a List of Notebooks, this list is parsed from a file by the Api. I would like to avoid reading/parsing the file every time I call my notebooks getter, hence I would like something like this:

  • if the file had already been parsed once, return the previously parsed List<Note> ;
  • else, read and parse the file, save the List<Note> and returns it.

I imagine something like this :

  List<Notebook> get notebooks {
    if (_notebooks != null) {
      return _notebooks;
    } else {
      return await _api.getNotebooks();
    }
  }

This code is not correct because I would need to mark the getter async and return a Future, which I don't want to. Do you know any solution for this problem, like caching values ? I also want to avoid initializing this list in my app startup and only parse once the first time the value is needed.

Christopher Moore
  • 15,626
  • 10
  • 42
  • 52
giga
  • 3
  • 2
  • Your operation ultimately depends on an asynchronous operation. Either you will need a separate asynchronous initialization step somewhere or the caching getter will need to be asynchronous. – jamesdlin Nov 17 '20 at 20:19

1 Answers1

0

you can create a singleton and you can store the data inside a property once you read it, from next time onwards you can use the same from the property.

You can refer this question to create a singleton

How do you build a Singleton in Dart?

Vilsad P P
  • 1,529
  • 14
  • 23