Home > Back-end >  Flutter file writing process
Flutter file writing process

Time:02-22

I am currently learning Dart and I have some problems related to file read/write.

I have a Bluetooth sensor sending me data (very fast) and after applying some processing methods on it, I would like to write it in a file. I have just realized that although I am receiving all data I need from Bluetooth, I am not writing them all in the file.

I have two files: one to read data and apply some processing on it and one to handle file operations.

// 1: Reading data and applying processing

var dataList = [];
Tuple2<String, List<List<double>>> dataParser(List<int> dataFromDevice) {
   ... // Some processing to obtain data
   dataList.add(data);
   if(dataList.isNotEmpty) FileStorage().writeFile();
}

I can see that all data I receive is well written in dataList.

// 2: File operations

class FileStorage{
  Future<String?> get _localPath async {
    final currentDirectory = await getApplicationDocumentsDirectory();
    return currentDirectory.path;
  }
  Future<File> get _localFile async {
    final currentPath = await _localPath;
    return File('$currentPath/A_B.bin');
  }
  Future writeFile() async {
    final file = await _localFile;
    await file.writeAsBytes(dataList[0], mode: FileMode.append).whenComplete(() => dataList.removeAt(0)
   }
}

The problem is actually occuring in writeFile() function. It is writing some data but for example if it had to write [1, 2, 3, 4, 5], it is writing [1, 4, ...].

I tried using some other techniques but failed. Any toughts on have I can achieve this, please?

Thank you very much.

CodePudding user response:

I found the problem after working on it for 1 day... I was sure that the problem was occurring in writeFile, because I checked dataList[0] and it contains what I want.

Apparently, this await _localFile was taking it's time with "taking the directory path, creating a new file, etc." and this was the moment I was losing my time and missing data.

Instead, I am now calling _localFile at the very beginning of data acquisition, instead of calling it every time in writeFile. It is logical though I didn't think await would lag my program this much.

  • Related