who-aditya-nawandar
who-aditya-nawandar

Reputation: 1344

Why does function (watcher) keep getting called repeatedly?

Future<void> _initializePhotoWatcher() async {
  if (await Permission.storage.isGranted) {
    // This gets the primary external storage directory, which may not directly be accessible in Android 10+
    _photoDirectory = Directory("/storage/emulated/0/DCIM/Camera");

    if (await _photoDirectory?.exists() ?? false) {
      final watcher = DirectoryWatcher(_photoDirectory!.path);
      watcher.events.listen((event) async {
        if (event.type == ChangeType.ADD) {
          // Cancel any existing timer for the same file
          _debounceMap[event.path]?.cancel();

          // Set a new timer for the file
          _debounceMap[event.path] = Timer(Duration(seconds: 2), () async {
            final file = File(event.path);
            if (await file.exists()) {
              _addStampToPhoto(file);
              // Optionally remove the entry from the map after processing
              _debounceMap.remove(event.path);
            }
          });
        }
      });
    } else {
      print("Camera directory does not exist or is not accessible");
    }
  } else {
    print("Need access to storage.");
  }
}

The _addStampToPhoto(file) function keeps getting called repeatedly.

Upvotes: 0

Views: 37

Answers (0)

Related Questions