When is a Dart private get function without backing field used?

165 Views Asked by At

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');
  }
}
1

There are 1 best solutions below

0
Ivo On

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.