how to cancel file reading operations in dart?

31 views Asked by At

I have dart code that opens a file as RandomAccessFile and reads from the file and stream the bytes to a video player through Http, but when the user seeks the video i need to set the position of the file to a new position and read again which throws an exception

FileSystemException: An async operation is currently pending

This is because the previous read request has not finished and i requested a new read. How can i cancel/dispose the old file read so i can read a new position?

1

There are 1 answers

0
Vonarian On

There is no direct way to do that, but you can create your helper function for that:

class FileHelper {
  bool _cancel = false;

  Future<void> fileReadWithCancel(String path) async {
    final file = File(path);
    final stream = file.openRead();
    final sub = stream.listen(null);

    sub.onData((data) {
      if (_cancel) {
        sub.cancel();
        print('Canceled!');
        return;
      }
      // Handle data.
    });
    sub.onError((error) {
      if (_cancel) {
        sub.cancel();
        print('Canceled!');
        return;
      }
      // Handle error with log from dart:developer or similar.
    });

    sub.onDone(() {
      // Good! :D
    });
  }

  void cancel() => _cancel = true;
}

Here's the class containing the helper function and using a _cancel flag. You stop reading content once you call the cancel method, and the stream is closed.

Here is an example:

import 'dart:io';

import 'package:flutter/material.dart';

Future<void> main() async {
  final helper = FileHelper();
  helper.fileReadWithCancel(path); //Path to your file.
  await Future.delayed(const Duration(seconds: 2));
  helper.cancel();
}

This represents a minimal example, you can modify and adapt it for your own code.