I am trying to build a flutter app for Android, to show all the directories and files inside a device directory, for example the '/storage/emulated/0'.
The app is able to show all the directories, but unfortunately the files do not show up.
I copy below the code of the main.dart file:
import 'dart:io';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'File Browser',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<FileSystemEntity> _files = [];
@override
void initState() {
super.initState();
_getFiles();
}
Future<void> _getFiles() async {
try {
Directory directory = Directory(
'/storage/emulated/0');
List<FileSystemEntity> files = directory.listSync();
setState(() {
_files = files;
});
} catch (e) {
print('Error reading directory: $e');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('File Browser'),
),
body: ListView.builder(
itemCount: _files.length,
itemBuilder: (context, index) {
FileSystemEntity file = _files[index];
return ListTile(
title: Text(file.toString()),
);
},
),
);
}
}
Searching on the internet I discovered that, since Android 11, some permissions are necessary to access the files.
So I added all the following permissions in the AndroidManifest.xml, but the files still do not show up.
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION"/>
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
For completion, I add below also the code of the pubspec.yaml file
name: file_browser
description: "A new Flutter project."
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
version: 1.0.0+1
environment:
sdk: '>=3.3.1 <4.0.0'
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.6
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^3.0.0
flutter:
uses-material-design: true
Thank you so much to anyone will try to help.