PreciseSpeech
PreciseSpeech

Reputation: 347

Trying to retrieve file length in flutter but I get the following exception -" FileSystemException: Cannot retrieve length of file"

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.

Upvotes: 3

Views: 7373

Answers (2)

Nabil alhafez
Nabil alhafez

Reputation: 458

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;

Upvotes: 3

almosaiki
almosaiki

Reputation: 71

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);

Upvotes: -1

Related Questions