0

I am going thru this example https://docs.flutter.dev/cookbook/persistence/reading-writing-files

The following class is defined with private get functions but there are no backing fields. What do they mean and when are they useful? Esp. _localPath and _localFile.

class CounterStorage {
  Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();

    return directory.path;
  }

  Future<File> get _localFile async {
    final path = await _localPath;
    return File('$path/counter.txt');
  }

  Future<int> readCounter() async {
    try {
      final file = await _localFile;

      // Read the file
      final contents = await file.readAsString();

      return int.parse(contents);
    } catch (e) {
      // If encountering an error, return 0
      return 0;
    }
  }

  Future<File> writeCounter(int counter) async {
    final file = await _localFile;

    // Write the file
    return file.writeAsString('$counter');
  }
}
Polymath
  • 630
  • 7
  • 11
  • https://stackoverflow.com/a/27691658/16827453 The getter and setter functions allow us to make the class appear to have a property, without a explicit property being declared. The property value may be calculated from other properties. – Polymath Nov 13 '22 at 01:48

1 Answers1

1

In essence, writing

Future<File> get _localFile async {
  final path = await _localPath;
  return File('$path/counter.txt');
}

is practically the same as writing a function like

Future<File> _localFile() async {
  final path = await _localPath;
  return File('$path/counter.txt');
}

I don't think there is a real difference, but I could be wrong. Only the way it's accessed is different then. For the first you need to write _localFile and the second you need to add parentheses like _localFile(). It's down to personal preference. The first notation is maybe useful if you expect to write a setter in the future as well.

Ivo
  • 18,659
  • 2
  • 23
  • 35