How to identify encoding standard of txt file in flutter/dart?

76 Views Asked by At

I use the file_picker package for my flutter app to provide the user with the possibility to select and import simple txt files. My code for this is currently as follows:

FilePickerResult? result = await FilePicker.platform.pickFiles();
if (result != null) {
  File file = File(result.files.single.path!);
  String fileContent = await file.readAsString();
  return fileContent;
}

Users mostly import txt files encoded in UTF-8, where everything works fine. But as it happens, some users try to import files in other encodings such as ANSI, which leads to a FormatException such as "FormatException: Missing extension byte (at offset 29)". Then, while the error can be catched by a try/catch clause, the file itself will not be imported.

In the FilePicker method, the relevant encoding standard that should be used can be specified.

But, how can I enable the app to find out which encoding has been used in a file?

I, myself, can manually find it out, for instance in Windows Notepad in the bottom right corner: enter image description here

But, I would need a way for the app to identify on its own when loading the file to then import it with the appropriate standard.

Do you have any idea how this can be done? Or any other idea how to handle this (maybe go through the 3-4 most common encoding standards)?

Many thanks in advance!

0

There are 0 best solutions below