Flutter - Select Single and Multiple Files From Device
Last Updated :
07 Mar, 2023
We will explore how to select single, or multiple files from our device with different conditions. Sometimes it happens that we want to select only a single type of file or with a fixed extension. If you are looking for the same just read the article till the end.
Step By Step Implementation
1. Create your flutter projectÂ
Dart
flutter create file_picker_template
2. Create a stateful widget with scaffold and create a simple Button in this scaffold
Dart
import 'package:flutter/material.dart';
class FilepickerScreen extends StatefulWidget {
const FilepickerScreen({super.key});
@override
State<FilepickerScreen> createState() => _FilepickerScreenState();
}
class _FilepickerScreenState extends State<FilepickerScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: FloatingActionButton(
onPressed: () {},
child: const Text("Select File"),
));
}
}
3. Add file picker package in pubscpec.yaml file
Dart
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
file_picker: ^5.2.4
4. Create a Variable for showing  and storing file
Dart
// Variable for
// showing single file
File? _file;
// Variable for
// showing multiple file
List<File?> _files;
5. File Picker Implementation
5.1. Single file
Dart
getFile() async {
FilePickerResult? result = await FilePicker.platform.pickFiles();
if (result != null) {
final file = File(result.files.single.path!);
_file = file;
setState(() {});
} else {
// User canceled the picker
// You can show snackbar or fluttertoast
// here like this to show warning to user
// ignore: use_build_context_synchronously
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Please select file'),
));
}
}
5.2. Multiple Files
Dart
getMultipleFile() async {
FilePickerResult? result =
await FilePicker.platform.pickFiles(allowMultiple: true,
type: FileType.any,
);
if (result != null) {
List<File?> file = result.paths.map((path) => File(path!)).toList();
file = files;
setState(() {});
} else {
// User canceled the picker and didn't
// select atleast 1 file from device
// You can show snackbar or fluttertoast
// here like this to show warning to user
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Please select atleast 1 file'),
));
}
}
6. Call the function on the button onpressed
6.1. Single File
Dart
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: FloatingActionButton.extended(
onPressed: () {
getFile();
},
label: const Text("Select File"),
)
6.2. Multiple File
Dart
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: FloatingActionButton.extended(
onPressed: () {
getMultipleFile();
},
label: const Text("Select File"),
)
7. To show the selected file in your app. You have to show depending on the file you selected and use it where you want.
For Testing, we have viewed like thisÂ
7.1. Single File
Dart
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
_file != null ? "File Name:- " : "No file is Selected",
textAlign: TextAlign.center,
style: const TextStyle(
color: Colors.black, fontWeight: FontWeight.bold),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text( _file != null ? _file!.path.split("/").last : "",
// To show name of file selected
textAlign: TextAlign.center,
style: const TextStyle(
color: Colors.black,
)),
],
)
],
)
7.2. Multiple File
Dart
ListView.builder(
itemCount: files.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text( files[index]!.path.split("/").last ,
// To show name of files selected
style: const TextStyle(color: Colors.black)),
);
},
)
Note: You can restrict which type of file  as well as the extension of the selected file
Dart
FilePicker.platform.pickFiles(
allowMultiple: true,
// You want to pass different argument
// in these 2 property in above function
type: FileType.audio,
allowedExtensions: ["pdf", "docx"]);
// 1.File type
// Expected arguments you can pass
// FileType.image // For selecting images only
// FileType.audio // For selecting file type related to audio
// FileType.media // For selecting file type related to any media include image,audio,video
// FileType.video // For selecting file type related to video
// FileType.custom // For selecting file type related to any custom file type which is not available in this list
// FileType.any // For selecting any type of file
// 2.allowedExtensions
// In this you pass a list of extensions you want to allowed to be selected from device
// Different extensions like png,pdf,jpg,jpeg,apk ,cls and many more
Full Source CodeÂ
1. Single File
Dart
import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
class SingleFilepickerScreen extends StatefulWidget {
const SingleFilepickerScreen({super.key});
@override
State<SingleFilepickerScreen> createState() => _SingleFilepickerScreenState();
}
class _SingleFilepickerScreenState extends State<SingleFilepickerScreen> {
// Variable for
// showing single file
File? _file;
getFile() async {
FilePickerResult? result = await FilePicker.platform.pickFiles();
if (result != null) {
final file = File(result.files.single.path!);
_file = file;
setState(() {});
} else {
// User canceled the picker
// You can show snackbar or fluttertoast
// here like this to show warning to user
// ignore: use_build_context_synchronously
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Please select file'),
));
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
_file != null ? "File Name:- " : "No file is Selected",
textAlign: TextAlign.center,
style: const TextStyle(
color: Colors.black, fontWeight: FontWeight.bold),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(_file != null ? _file!.path.split("/").last : "",
textAlign: TextAlign.center,
style: const TextStyle(
color: Colors.black,
)),
],
)
],
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: FloatingActionButton.extended(
onPressed: () {
getFile();
},
label: const Text("Select File"),
));
}
}
2. Multiple File
Dart
import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
class MultipleFilepickerScreen extends StatefulWidget {
const MultipleFilepickerScreen({super.key});
@override
State<MultipleFilepickerScreen> createState() =>
_MultipleFilepickerScreenState();
}
class _MultipleFilepickerScreenState extends State<MultipleFilepickerScreen> {
getMultipleFile() async {
FilePickerResult? result = await FilePicker.platform.pickFiles(
allowMultiple: true,
// You want to pass different argument
// in these 2 property in above function
);
// 1.File type
// Expected arguments you can pass
// FileType.image // For selecting images only
// FileType.audio // For selecting file type related to audio
// FileType.media // For selecting file type related to any media include image,audio,video
// FileType.video // For selecting file type related to video
// FileType.custom // For selecting file type related to any custom file type which is not available in this list
// FileType.any // For selecting any type of file
// 2.allowedExtensions
// In this you pass a list of extensions you want to allowed to be selected from device
// Different extensions like png,pdf,jpg,jpeg,apk ,cls and many more
if (result != null) {
List<File?> file = result.paths.map((path) => File(path!)).toList();
files = file;
setState(() {});
} else {
// User canceled the picker and didn't select atleast 1 file from device
// You can show snackbar or fluttertoast here like this to show warning to user
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Please select atleast 1 file'),
));
}
}
// Variable for showing multiple file
List<File?> files = [];
@override
Widget build(BuildContext context) {
print(files);
return Scaffold(
body: ListView.builder(
itemCount: files.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(files[index]!.path.split("/").last,
style: TextStyle(color: Colors.black)),
);
},
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: FloatingActionButton.extended(
onPressed: () {
// Function for
// selecting multiple files
getMultipleFile();
},
label: const Text("Select File"),
));
}
}
Similar Reads
Flutter - Pick and Open Files From Storage Sometimes in an app, we need to pick and open a file from the phone's storage, in this article, we will achieve the same using file_picker and open_file flutter packages. 1. Create an App: Create a new flutter app by running the below command on your terminal: flutter create your_app_name Now open y
5 min read
How to Select Video from Camera and Gallery in Flutter? We can add video from the gallery as well as from the camera using the image_picker package in Flutter. For this, youâll need to use your real device or web version. Follow the below steps to display the images from the gallery: Step By Step Implementation Step 1: Create a New Project in Android Stu
4 min read
Flutter - Create an Excel Sheet and Save the File in Device A spreadsheet is a computer program that captures, displays, and manipulates data arranged in rows and columns. Sometimes we have data but that is either in json or in the list and we have to convert data to an excel sheet and store it in the user's device. So that he/she can easily access it, you m
3 min read
Flutter - Filter a List Using Some Condition In Flutter, the where() method can be used on a list to filter its elements based on a specified condition. To demonstrate this let's make a Flutter app that will contain a List of products having name, category and price. Then we create a TextView named a Filtered list by price when the user enters
6 min read
Flutter - Read, Write and Override File Locally to Disk In many cases, we need to save files locally so that we can read and write them while the device is offline. For example, we might need to persist data across the app. To save files to disk on mobile or desktop apps, we need to add package path_provider to our project. There are Four Steps to Read a
8 min read
Flutter - Store User Details Using Firebase Firebase is a product of Google that helps developers to build, manage, and grow their apps easily. It helps developers to build their apps faster and in a more secure way. No programming is required on the Firebase side which makes it easy to use its features more efficiently. It provides services
3 min read