Fetch content from android directory

Viewed 150

I'm trying to fetch data(mp3) from my app's directory itself and display in ListView() i.e, path:/storage/emulated/0/Android/data/com.example.MyApp/files

for which I've used getExternalStorageDirectory() to save my file there but all I get using below code is just notification sounds. I need data from above path only. Guide me

import 'dart:io';
import 'package:cast/utilities/bottom_sheet_widget.dart';
import 'package:flutter/material.dart'; 
import 'package:flutter/widgets.dart';

class MyAudioList extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _MyAudioList(); //create state
}
}

class _MyAudioList extends State<MyAudioList> {
var files;
List? allSongs;

void getFiles() async {
//asyn function to get list of files
Directory dir =
    
Directory('/storage/emulated/0/Android/data/com.example.cast/files');
String mp3Path = dir.toString();
print(mp3Path);
List<FileSystemEntity> _files;
List<FileSystemEntity> _songs = [];
_files = dir.listSync(recursive: true, followLinks: false);
for (FileSystemEntity entity in _files) {
  String path = entity.path;
  if (path.endsWith('.mp3')) _songs.add(entity);
}
print(_songs);
// print(_songs.length);
setState(() {
  files = _files;
  allSongs = _songs;
}); //update the UI
}

@override
void initState() {
getFiles(); //call getFiles() function on initial state.
super.initState();
 }

@override
Widget build(BuildContext context) {
return RefreshIndicator(
  onRefresh: () async {
    getFiles();
  },
  child: Scaffold(
      body: files == null
          ? Center(
              child: Text(
              'Seaching..',
              style: TextStyle(color: Colors.white),
            ))
          : ListView.builder(
              //if file/folder list is grabbed, then show here
              itemCount: allSongs!.length, //_songs.length ?? 0,
              itemBuilder: (context, index) {
                return ListTile(
                  key: UniqueKey(),
                  leading: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      ClipRRect(
                        borderRadius: BorderRadius.circular(8),
                        child: Image.network(
                          "https://images.unsplash.com/photo- 
       1541963463532-d68292c34b19?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8Ym9va3xlbnwwfHwwfHw%3D&w=1000&q=80",
                          width: 50,
                          height: 50,
                          fit: BoxFit.cover,
                        ),
                      ),
                    ],
                  ),
                  title: Text(
                    '$allSongs',
                    maxLines: 1,
                    style: const TextStyle(
                      color: Colors.white,
                      fontWeight: FontWeight.w400,
                    ),
                  ),
                  subtitle: Text(
                    "publisher",
                    style: TextStyle(
                      color: Colors.grey[400]!,
                      fontSize: 13,
                    ),
                  ),
                  trailing: Row(mainAxisSize: MainAxisSize.min, 
   children: [
                    IconButton(
                      onPressed: () {},
                      icon: Icon(Icons.more_vert, color: 
   Colors.grey),
                    )
                  ]),
                );
              },
            )),
);
}
}
1 Answers

To list all the files or folders, you have to use flutter_file_manager, path, and path_provider_ex flutter package. Add the following lines in your pubspec.yaml file to add this package in your dependency.

dependencies:
  flutter:
    sdk: flutter
  path: ^1.6.4
  path_provider_ex: ^1.0.1
  flutter_file_manager: ^0.2.0

Add read / write permissions in your android/app/src/main/AndroidManifest.xml before tag.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

If you still get the Permission Denied error, add the following line on AndroidManifest.xml file.

<application
      android:requestLegacyExternalStorage="true"

see the explanation in the comment.

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_file_manager/flutter_file_manager.dart';
import 'package:path_provider_ex/path_provider_ex.dart';
//import package files

void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return  MaterialApp(
          home: MyFileList(), //call MyFile List 
    );
  }
}

//apply this class on home: attribute at MaterialApp()
class MyFileList extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    return _MyFileList();
  }
}

class _MyFileList extends State<MyFileList>{
  var files;
 
  void getFiles() async { //asyn function to get list of files
      List<StorageInfo> storageInfo = await PathProviderEx.getStorageInfo();
      var root = storageInfo[0].rootDir; //storageInfo[1] for SD card, geting the root directory
      var fm = FileManager(root: Directory(root)); //
      files = await fm.filesTree( 
      //set fm.dirsTree() for directory/folder tree list
        excludedPaths: ["/storage/emulated/0/Android"],
        extensions: ["mp3"] //optional, to filter files, remove to list all,
        //remove this if your are grabbing folder list
      );
      setState(() {}); //update the UI
  }

  @override
  void initState() {
    getFiles(); //call getFiles() function on initial state. 
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title:Text("File/Folder list from SD Card"),
        backgroundColor: Colors.redAccent
      ),
      body:files == null? Text("Searching Files"):
           ListView.builder(  //if file/folder list is grabbed, then show here
              itemCount: files?.length ?? 0,
              itemBuilder: (context, index) {
                    return Card(
                      child:ListTile(
                         title: Text(files[index].path.split('/').last),
                         leading: Icon(Icons.image),
                         trailing: Icon(Icons.delete, color: Colors.redAccent,),
                      )
                    );
              },
          )
    );
  }
}
Related