Connect with us

Uncategorized

Flutter File Picker: Seamless File Selection for Your App

Published

on

File selection made easy in Flutter! Learn how to use File Picker in Flutter to allow users to select files effortlessly.

What is File Picker in Flutter?

File Picker is a Flutter plugin that enables users to select files from their device storage. Whether it’s images, documents, audio, or videos, File Picker simplifies the process of accessing files within a Flutter application.

Why Use File Picker in Flutter?

Flutter’s default file handling capabilities are limited, but File Picker provides flexibility by:

  • Allowing users to select single or multiple files.
  • Supporting various file types like images, PDFs, and ZIP files.
  • Enabling file selection from external storage and cloud services.

Installing File Picker Plugin

To use File Picker, add the dependency to your pubspec.yaml file:

yaml

CopyEdit

dependencies:

  file_picker: ^6.1.1  # Use the latest version

Then, run:

sh

CopyEdit

flutter pub get

This command fetches and installs the package.

Importing File Picker

After installation, import the package into your Dart file:

dart

CopyEdit

import ‘package:file_picker/file_picker.dart’;

Now, you’re ready to implement file selection in your app.

Picking a Single File in Flutter

To allow users to pick a single file, use the following code:

dart

CopyEdit

void pickSingleFile() async {

  FilePickerResult? result = await FilePicker.platform.pickFiles();

  if (result != null) {

    String filePath = result.files.single.path!;

    print(“Selected file: $filePath”);

  } else {

    print(“File selection canceled”);

  }

}

This function opens the file picker, and if the user selects a file, its path is printed in the console.

Picking Multiple Files

For selecting multiple files, modify the function:

dart

CopyEdit

void pickMultipleFiles() async {

  FilePickerResult? result = await FilePicker.platform.pickFiles(allowMultiple: true);

  if (result != null) {

    List<String> files = result.files.map((file) => file.path!).toList();

    print(“Selected files: $files”);

  } else {

    print(“File selection canceled”);

  }

}

This function enables multiple file selection and stores the file paths in a list.

Filtering Specific File Types

To restrict users to selecting only certain types of files, specify the file type:

dart

CopyEdit

void pickPDFFile() async {

  FilePickerResult? result = await FilePicker.platform.pickFiles(

    type: FileType.custom,

    allowedExtensions: [‘pdf’],

  );

  if (result != null) {

    String filePath = result.files.single.path!;

    print(“Selected PDF file: $filePath”);

  } else {

    print(“File selection canceled”);

  }

}

This ensures only .pdf files can be selected. You can replace pdf with other extensions like jpg, mp3, or txt as needed.

Picking Files from External Storage

Some apps need to access files from external storage. The File Picker plugin supports external storage access, but you must request permissions on Android.

Update your AndroidManifest.xml file:

xml

CopyEdit

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

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

This allows the app to read files from external storage.

Saving Picked Files in App Directory

After picking a file, you may want to save it within your app’s directory. Use path_provider to get the app’s directory and move the file:

dart

CopyEdit

import ‘dart:io’;

import ‘package:path_provider/path_provider.dart’;

void savePickedFile(String filePath) async {

  final directory = await getApplicationDocumentsDirectory();

  final fileName = filePath.split(‘/’).last;

  final newFilePath = ‘${directory.path}/$fileName’;

  File(filePath).copy(newFilePath);

  print(“File saved to: $newFilePath”);

}

This function copies the selected file to the app’s document directory.

Displaying Picked Files in UI

After picking files, displaying them in the UI is essential. Use a ListView to show the selected file names:

dart

CopyEdit

import ‘package:flutter/material.dart’;

class FilePickerScreen extends StatefulWidget {

  @override

  _FilePickerScreenState createState() => _FilePickerScreenState();

}

class _FilePickerScreenState extends State<FilePickerScreen> {

  List<String> pickedFiles = [];

  void pickFiles() async {

    FilePickerResult? result = await FilePicker.platform.pickFiles(allowMultiple: true);

    if (result != null) {

      setState(() {

        pickedFiles = result.files.map((file) => file.name).toList();

      });

    }

  }

  @override

  Widget build(BuildContext context) {

    return Scaffold(

      appBar: AppBar(title: Text(“File Picker”)),

      body: Column(

        children: [

          ElevatedButton(onPressed: pickFiles, child: Text(“Pick Files”)),

          Expanded(

            child: ListView.builder(

              itemCount: pickedFiles.length,

              itemBuilder: (context, index) {

                return ListTile(title: Text(pickedFiles[index]));

              },

            ),

          ),

        ],

      ),

    );

  }

}

This UI displays a button to pick files and a list of selected file names.

Uploading Picked Files to a Server

If your app needs to upload files to a server, use http to send a POST request:

dart

CopyEdit

import ‘package:http/http.dart’ as http;

import ‘dart:io’;

void uploadFile(String filePath) async {

  var request = http.MultipartRequest(

    ‘POST’,

    Uri.parse(‘https://yourserver.com/upload’),

  );

  request.files.add(await http.MultipartFile.fromPath(‘file’, filePath));

  var response = await request.send();

  if (response.statusCode == 200) {

    print(“File uploaded successfully!”);

  } else {

    print(“File upload failed.”);

  }

}

Replace https://yourserver.com/upload with your actual API endpoint.

Handling Errors and Edge Cases

 File Picker

To enhance user experience, handle errors such as:

  • Permission Denied: Request permissions properly on Android and iOS.
  • No File Selected: Display a message if the user cancels the selection.
  • Large Files: Restrict file size before uploading.

Conclusion

File Picker in Flutter simplifies file selection, allowing users to choose files effortlessly from their device storage. Whether picking a single file, multiple files, or filtering specific types, the plugin offers flexibility and ease of use. Integrating File Picker can enhance your app’s functionality, making file management more efficient.

FAQs

Can File Picker select multiple files at once?
Yes, set allowMultiple: true when calling pickFiles() to enable multiple file selection.

Does File Picker work on both Android and iOS?
Yes, the plugin is cross-platform and works on both Android and iOS with proper permissions.

How do I allow only specific file types?
Use the allowedExtensions parameter to filter file types like PDFs, images, or videos.

Can I upload a picked file to a server?
Yes, you can use http to send the file via a POST request to an API endpoint.

How do I save the picked file in local storage?
Use the path_provider package to get the app’s document directory and save the file there.

Continue Reading
Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Trending