2

I am trying to download some files in a flutter application. After the files are downloaded, I want to be able to show the downloads to the user with files and their information like date modified, size etc. Right now I am retrieving list of files like this:

import 'dart:io' as io;

import 'package:flutter/material.dart';
import 'package:open_file/open_file.dart';
import 'package:path_provider/path_provider.dart';

class Downloads extends StatefulWidget {
  @override
  _DownloadsState createState() => _DownloadsState();
}

class _DownloadsState extends State<Downloads> {
  String directory;
  List file = new List();
  @override
  void initState() {
    super.initState();
    _listofFiles();
  }

  void _listofFiles() async {
    directory = (await getExternalStorageDirectory()).path;
    setState(() {
      file = io.Directory("$directory/").listSync();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Downloads"),
      ),
      body: GridView.builder(
          padding: EdgeInsets.all(10),
          gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              mainAxisSpacing: 10,
              crossAxisSpacing: 10,
              childAspectRatio: 0.9),
          itemCount: file.length,
          itemBuilder: (context, i) {
            print(file[i]);
            return GestureDetector(
              onTap: () {
                OpenFile.open(file[i].toString());
              },
              child: Container(
                padding: EdgeInsets.all(10),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(4),
                    color: Colors.white,
                    boxShadow: [
                      BoxShadow(
                          color: Colors.grey, blurRadius: 2, spreadRadius: 2),
                    ]),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: <Widget>[
                    Icon(
                      Icons.insert_drive_file,
                      size: 50,
                      color: Colors.blue,
                    ),
                    SizedBox(height: 10),
                    Text(file[i].toString())
                  ],
                ),
              ),
            );
          }),
    );
  }
}

But I am only able to get the file path from the above code and not the fileName and file extension or file size. How do I retrieve those information?

Zero Live
  • 1,653
  • 5
  • 22
  • 44
  • When you have a path you can create a File object. https://api.dart.dev/stable/2.7.2/dart-io/File-class.html It has a length attribute. With a bit of regex or string.split you can find out the name and extension yourself. – Saskia Apr 12 '20 at 17:05
  • While it does work, it has some flaws. Like it returns path as [File: '/storage/emulated/0/Android/data/com.example.test_app/files/picture.jpg']. So it isn't exactly path. And I don't get information like size and date modified etc. – Zero Live Apr 13 '20 at 05:57
  • That looks like a path to me. You are calling to string on a File object. You have to call `.path` or `.absolute` to get the path as string. Maybe a general dart tutoria could help you understand these concepts before diving into flutter. Have a look at: https://dart.dev/tutorials/server/cmdline – Saskia Apr 13 '20 at 09:17
  • Yes, I was able to figure that out . directory returns FileSystemEntity which is not quite File object. Once I did "is File" check I was able to retrieve path from the returned string. Thanks. – Zero Live Apr 13 '20 at 09:46
  • I've tried to run your sample code and got nothing just [this](https://i.stack.imgur.com/O4Wca.png). It seems that you've solve the error. It would be nice if you could provide the solution and accept it as an answer. – MαπμQμαπkγVπ.0 Apr 27 '21 at 22:10

1 Answers1

0

You can use FileSystemEntity to fetch the file's metadata with FileStat. Follow similar steps here to cast FileSystemEntity on Files in the directory.

Filter supported file extensions with regex.

List<FileSystemEntity> listFiles = [];
_fetchFiles(Directory dir) {
  dir.list().forEach((element) {
    RegExp regExp =
        new RegExp("\.(gif|jpe?g|tiff?|png|webp|bmp)", caseSensitive: false);
    debugPrint('dir contains: $element is image? ${regExp.hasMatch('$element')}');
    // Only add in List if file in path is supported
    if (regExp.hasMatch('$element')) {
      listFiles.add(element);
    }   
  });
}

To fetch FileStat from FileSystemEntity, FileSystemEntity.stat() can be called.

listFiles[index].stat().then((FileStat stat){
  // Access file metadata using FileStat 
  // https://api.flutter.dev/flutter/dart-io/FileStat-class.html
});
Omatt
  • 8,564
  • 2
  • 42
  • 144