File Picker Package for Flutter: How to Use the Native File Explorer in Your Flutter App

Published on by Flutter News Hub

File Picker Package for Flutter: How to Use the Native File Explorer in Your Flutter App

The File Picker plugin allows you to easily pick files from a user's device. It supports multiple platforms, including Android, iOS, macOS, Windows, Linux, and Web. In this tutorial, we'll show you how to use the File Picker plugin to pick files with custom filters.

Installation

  1. Add the File Picker plugin to your Flutter project's pubspec.yaml file:
dependencies:
  file_picker: ^4.7.1

Usage

To use the File Picker plugin, you can use the FilePicker.platform.pickFiles() method. This method returns a FilePickerResult object, which contains a list of PlatformFile objects.

The PlatformFile object contains information about the selected file, such as the file name, path, size, and extension.

Here's an example of how to pick a single file with a custom filter:

import 'package:file_picker/file_picker.dart';

void main() async {
  FilePickerResult? result = await FilePicker.platform.pickFiles(
    type: FileType.custom,
    allowedExtensions: ['jpg', 'pdf', 'doc'],
  );

  if (result != null) {
    PlatformFile file = result.files.first;

    print(file.name);
    print(file.bytes);
    print(file.size);
    print(file.extension);
    print(file.path);
  } else {
    // User canceled the picker
  }
}

You can also pick multiple files with a custom filter:

import 'package:file_picker/file_picker.dart';

void main() async {
  FilePickerResult? result = await FilePicker.platform.pickFiles(
    type: FileType.custom,
    allowedExtensions: ['jpg', 'pdf', 'doc'],
    allowMultiple: true,
  );

  if (result != null) {
    List files = result.files;

    for (PlatformFile file in files) {
      print(file.name);
      print(file.bytes);
      print(file.size);
      print(file.extension);
      print(file.path);
    }
  } else {
    // User canceled the picker
  }
}

Conclusion

The File Picker plugin is a powerful tool for picking files from a user's device. It supports multiple platforms and allows you to use custom filters to select specific types of files.

Additional Resources

Flutter News Hub