2

I am trying to access the length of the file using the following code:-

File file = File('/storage/emulated/0/Android/data/com.example.mynewapp/files/Pictures/IMG_20200322_202358.jpg');
final length = await file.length();

and I get the following exception-

FileSystemException: Cannot retrieve length of file, path = '/storage/emulated/0/Android/data/com.example.mynewapp/files/Pictures/IMG_20200322_202358.jpg'

I followed the suggestions from the post and tried without the await:-

final length = file.lengthSync();

also

final length = File(file.resolveSymbolicLinksSync()).lengthSync()

but I end up getting the same exception.

PreciseSpeech
  • 317
  • 4
  • 9

2 Answers2

3

Here is a solution using a function that will provide you with the file size as a neat formatted string.

Imports:

import 'dart:io';
import 'dart:math';

Output:

File image = new File('image.png');
print(getFilesizeString(bytes: image.lengthSync()}); // Output: 17kb, 30mb, 7gb

Function:

// Format File Size
static String getFileSizeString({@required int bytes, int decimals = 0}) {
  const suffixes = ["b", "kb", "mb", "gb", "tb"];
  var i = (log(bytes) / log(1024)).floor();
  return ((bytes / pow(1024, i)).toStringAsFixed(decimals)) + suffixes[i];
}

If you want to just get a length without caring about the unit so you do care about the size condintionaly You can get the file size by this code :

final bytes = image.readAsBytesSync().lengthInBytes; 
final kb = bytes / 1024; 
final mb = kb / 1024;
Nabil alhafez
  • 190
  • 1
  • 7
-1

do you have a Permission to read this file ? try to check that then use the lengthSync to get the value directly and not a future of the Value i tryed that and it is work after i add the storge Permission

File f = new File('your path');
s = f.lengthSync()
print(s);
almosaiki
  • 71
  • 5
  • Yes, I have the permission to read this file and cross checked by trying to print the file. After checking this I also tried file.lengthSync() and end up with the same exception. – PreciseSpeech Mar 23 '20 at 10:50