Home > other >  how to convert my file size to mb, kb, gb etc in flutter
how to convert my file size to mb, kb, gb etc in flutter

Time:11-25

i want to get size of file after getting file from storage here is my code to get size

 trailing: FutureBuilder<int>(
                        builder: (context, snapshot) {
                          return Text(snapshot.data.toString());
                        },
                        future: files[index].length(),
                      ),

CodePudding user response:

Hey here is my edited code relevant for your question buddy. I have used [file_picker][1] this package to pick files from my device storage.

used the below function to get the size of the picked file

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];
    }

I Got the file size int from PlatformFile like below

getFileSizeString(bytes: snapshot.data!.files[0].size);

And got the expected result of the file size. Shared the full code here, please check it.

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

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:file_picker/file_picker.dart';


class imagePicker extends StatefulWidget {
  imagePicker({Key? key}) : super(key: key);

  @override
  State<imagePicker> createState() => _imagePickerState();
  
}

class _imagePickerState extends State<imagePicker> {


File? fileName;

Future<FilePickerResult?> pickFiles()async{
  final result = await FilePicker.platform.pickFiles(
    allowMultiple: false,
  );
  return result;
}

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];
    }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      builder: (context, snapshot) {
        if (snapshot.hasData){
          getFileSizeString(bytes: snapshot.data!.files[0].size);
          
          return Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(snapshot.data!.files[0].name),
              Text(getFileSizeString(bytes: snapshot.data!.files[0].size)),
            ],
          );
        }else{
          return Text("waiting");
        }
      },
      future: pickFiles(),
    );
  }
}

Happy coding ! [1]: https://pub.dev/packages/file_picker

  • Related