Flutter File Picker | Pick Images ,Video, Audio, Docs etc.| FilePicker Example
Hello Guys, Welcome to Codes With Sunny. In this flutter tutorial article, will explore how to pick files(images,video,audio, docs etc.) in flutter app.
A package that allows you to use the native file(images,video,audio) explorer to pick single or multiple files at times.
File Picker
This package is very easily to use to pick file(images,video,audio) from native file explorer, it allows you to use file explorer of native platform to pick files , if support single & multiple file picking & also extension filtering is supported in selecting files in this app.
Step 1: Add the Dependency to pubspec.yaml file as shown below:
dependencies:
file_picker: ^4.1.6
Step 2: Import the library
Now in your Dart code, you can use:
import 'package:file_picker/file_picker.dart';
Pick Single File :
FilePickerResult? results = await FilePicker.platform.pickFiles(); if (results != null)
{
File files = File(results.files.single.path);
}
else {}
Pick Multiple files :
FilePickerResult? results = await FilePicker.platform.pickFiles(allowMultiple: true);
if (results != null)
{
List files = result.paths.map((path) => File(path)).toList();
}
else {}
Multiple files with extension filter :
FilePickerResult? results = await FilePicker.platform.pickFiles( type: FileType.custom,
allowedExtensions: ['jpg', 'png', 'pdf', 'doc'], );
Get Full Details of picked file in flutter :
fileDetails(PlatformFile file) {
final kb = file.size / 1024;
final mb = kb / 1024;
final size = (mb >= 1)
? '${mb.toStringAsFixed(2)} MB'
: '${kb.toStringAsFixed(2)} KB';
return Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('File Name : ${file.name}'),
Text('File Size : $size'),
Text('File Extension : ${file.extension ?? 'Unknown'}'),
Text('File Path : ${file.path ?? 'Path not available'}'),
],
),
);
}
Note: I am using OpenFile package to open the user selected or picked file
OpenFile
A plugin that can call native APP to open files with string result in flutter app, support iOS(DocumentInteraction) / android(intent) / PC(ffi) / web(dart:html) etc.
Step 1: Add the Dependency to pubspec.yaml file as shown below:
dependencies: open_file: ^3.2.1
Step 2: Import the library Now in your Dart code, you can use:
import 'package:open_file/open_file.dart';
Snippet Code
void
viewFile(PlatformFile file)
{
OpenFile.open(file.path);
}