Category

Flutter

Category

2 Flutter Folder Picker Examples with Tutorial

Hi, Welcome to AndroidRide.

Sometimes, users need to pick directories to store their data or download files. In this post, you will learn how to pick directories using two flutter packages.

okay..Let’s start then.

Let’s create a Flutter project – Check this tutorial, if you are a beginner.

How To Pick Folder Using easy_folder_picker package – Only Android.

flutter folder picker using easy_folder_picker

You can also use Flutter command to create project.

I am using Flutter 2.5.1
Dart: 2.12.0

You need to import the dependency in pubspec.yaml file.


  easy_folder_picker: ^1.1.1

flutter folderpicker permissions

Also, import these permissions in android/app/src/main/AndroidManifest.xml.


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

//if you want to create folders by users

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

//In Android Q
<application
      android:requestLegacyExternalStorage="true"

Now this package only supports Android. It handles requesting permissions as well. Next you need to set compileSdkVersion to 31 in android/app/build.gradle


android {
  compileSdkVersion 31

  • FolderPicker.ROOTPATH: “/storage/emulated/0/”
  • When the ElevatedButton taps it calls _selectDirectory().
  • FolderPicker.pick() return which directory you have selected.
  • Using setState method, we will rebuild the UI.

 Directory? selectedDirectory;

  void _selectDirectory(BuildContext context) async {
    Directory? directory = selectedDirectory;
    directory ??= Directory(FolderPicker.ROOTPATH);

      Directory? newDirectory = await FolderPicker.pick(
      allowFolderCreation: true,
      context: context,
      rootDirectory: directory,
    );

    setState(() {
      selectedDirectory = newDirectory;
      //print(selectedDirectory);
    });
  }


Here we go, the complete code is here.

Complete Source Code


import 'dart:io';
import 'package:easy_folder_picker/FolderPicker.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Folder Picker',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const FolderPickerScreen(),
    );
  }
}

class FolderPickerScreen extends StatefulWidget {
  const FolderPickerScreen({Key? key}) : super(key: key);

  @override
  _FolderPickerScreenState createState() => _FolderPickerScreenState();
}

class _FolderPickerScreenState extends State<FolderPickerScreen> 
{
  Directory? selectedDirectory;

  void _selectDirectory(BuildContext context) async {
    Directory? directory = selectedDirectory;
    directory ??= Directory(FolderPicker.ROOTPATH);
      Directory? newDirectory = await FolderPicker.pick(
      allowFolderCreation: true,
      context: context,
      rootDirectory: directory,
    );

    setState(() {
      selectedDirectory = newDirectory;
      //print(selectedDirectory);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter Folder Picker Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: () {
                _selectDirectory(context);
              },
              child: const Text('Select Directory'),
            ),
            const SizedBox(
              height: 10,
            ),
            selectedDirectory == null
                ? const Text('No directory selected')
                : Text("Directory Path: ${selectedDirectory!.path}")
          ],
        ),
      ),
    );
  }
}


Flutter folder Picker Using filesystem_picker package

folder picker filesystem_picker package
In this example, we will use filesystem_picker package.
You need to add below dependencies in pubspec.yaml file.


filesystem_picker: ^2.0.0
permission_handler: ^8.2.5

Also, import these permissions in android/app/src/main/AndroidManifest.xml.


<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

  • _prepareStorage() method initialize the rootPath to ‘/storage/emulated/0/’.
  • FilesystemPicker.open() return path of the selected directory.
  • Rebuilds UI using setState method.

Future<void> _prepareStorage() async 
  {
    rootPath = Directory('/storage/emulated/0/');
    setState(() {});
  }

  Future<void> _pickDir(BuildContext context) async 
  {
  
    String? path = await FilesystemPicker.open(
      title: 'Select folder',
      context: context,
      rootDirectory: rootPath!,
      fsType: FilesystemType.folder,
      pickText: 'Select this folder',
      folderIconColor: Colors.teal,
      requestPermission: () async =>
          await Permission.storage.request().isGranted,
    );

    setState(() {
      dirPath = path;
    });
  }


Full Source Code


import 'dart:io';
import 'package:filesystem_picker/filesystem_picker.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';

void main() 
{
  runApp(
    const MaterialApp(
      home: MyApp(),
    ),
  );
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Directory? rootPath;
  String? dirPath;

  @override
  void initState() {
    super.initState();
    _prepareStorage();
  }

  Future<void> _prepareStorage() async 
  {
    rootPath = Directory('/storage/emulated/0/');
    setState(() {});
  }

  Future<void> _pickDir(BuildContext context) async 
  {
  
    String? path = await FilesystemPicker.open(
      title: 'Select folder',
      context: context,
      rootDirectory: rootPath!,
      fsType: FilesystemType.folder,
      pickText: 'Select this folder',
      folderIconColor: Colors.teal,
      requestPermission: () async =>
          await Permission.storage.request().isGranted,
    );

    setState(() {
      dirPath = path;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Directory Picker'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            dirPath != null
                ? Padding(
                    padding: const EdgeInsets.symmetric(vertical: 10),
                    child: Text('$dirPath'),
                  )
                : const Padding(
                    padding: EdgeInsets.symmetric(vertical: 10),
                    child: Text('No directory selected'),
                  ),
            ElevatedButton(
              child: const Text('Select directory'),
              onPressed: (rootPath != null) ? () => _pickDir(context) : null,
            ),
          ],
        ),
      ),
    );
  }
}


if you like this post, please share it with your family and friends.
Thanks.

Please disable your adblocker or whitelist this site!