flutter_document_picker 4.0.0

  • Readme
  • Changelog
  • Example
  • Installing
  • 95

flutter_document_picker #

Allows user pick a document. Picked document is copied to app temporary directory. Optionally allows pick document with specific extension only.

When file is picked its extension is checked using allowedFileExtensions parameter. Then file is copied to app temp directory. Copied file path is returned as result. If picked file extension is not in allowedFileExtensions list then extension_mismatch error is returned.

In Android Intent.ACTION_OPEN_DOCUMENT is used. This intent is supported only from Android 19 (KitKat) SDK version. So this plugin can be used only if app minSdkVersion is 19 or more.

In iOS UIDocumentPickerViewController is used. Files can be filtered by list of UTI types using allowedUtiTypes parameter. Picked file path is returned as result.

Params #

Plugin has 3 optional parameters to help pick only specific document type:

  • List<String> allowedUtiTypes (used only in iOS)

    In iOS Uniform Type Identifiers is used to check document types. If list is null or empty "public.data" document type will be provided. Only documents with provided UTI types will be enabled in iOS document picker.

    More info: https://developer.apple.com/library/archive/qa/qa1587/_index.html

  • List<String> allowedFileExtensions (used both in iOS and in Android)

    List of file extensions that picked file should have. If list is null or empty - picked document extension will not be checked.

  • List<String> allowedMimeTypes (used only in Android)

    Only files with provided MIME types will be shown in document picker. If list is null or empty - */* MIME type will be used.

  • List<String> invalidFileNameSymbols (used both in iOS and in Android)

    List symbols that will be sanitized to "_" in the selected document name. I.e. Google Drive allows symbol '/' in the document name, but this symbol is not allowed in file name that will be saved locally.

    Default list: ['/'].

    Example: file name 'Report_2018/12/08.txt' will be replaced to 'Report_2018_12_08.txt'

Example #

//Without parameters:
final path = await FlutterDocumentPicker.openDocument();
  
  ...

    
//With parameters:
FlutterDocumentPickerParams params = FlutterDocumentPickerParams(      
  allowedFileExtensions: ['mwfbak'],
  allowedUtiTypes: ['com.sidlatau.example.mwfbak'],
  allowedMimeTypes: ['application/*'],
  invalidFileNameSymbols: ['/'],
);

final path = await FlutterDocumentPicker.openDocument(params: params);

Getting Started #

For help getting started with Flutter, view our online documentation.

For help on editing plugin code, view the documentation.

4.0.0 #

  • Support Android V2 embedding.
  • Specify that this plugin is for Android / iOS platforms only.

3.0.1 #

  • Fixed crash in Android when plugin is used without activity (issue #30). Special thanks to @@LinusU for fixing the issue!

3.0.0 #

  • Added ability to filter by multiple MIME types in Android.

BREAKING:

allowedMimeType parameter is replaced with allowedMimeTypes.

MIGRATION:

Just change allowedMimeType: 'value' to array allowedMimeTypes: ['value']

2.0.0 #

  • Migrated to Android X.

1.4.0 #

  • Updated to work with Android Studio 3.3.

1.3.0 #

  • Updated Swift version to 4.2.

1.2.0 #

  • Added ability to sanitize selected document name (Issue #17).

1.1.3 #

  • Updated Gradle, Kotlin, target SDK versions to latest ones.

1.1.2 #

  • Updated Gradle, Kotlin, target SDK versions to latest ones (Issue #11).

1.1.1 #

  • Fixed bug when plugin reacted to not its own request codes (Issue #6). Special thanks to @acheronian for spotting the issue!

1.1.0 #

  • Added allowedMimeType parameter to filter files by MIME type in Android.

1.0.1 #

  • Fixed bug when small file got corrupted after copying (Issue #3). Special thanks to @przemyslawsikora for spotting the issue!

1.0.0 #

  • Changed API to support list of allowed file extensions and UTI's.

0.1.1 #

  • Android part: Not needed logging removed.

0.1.0 #

  • iOS part: picked document is copied to temp dir.

0.0.3 #

  • Removed print statements.

0.0.2 #

  • Fixed documentation.

0.0.1 #

  • Initial version that works on Android and iOS. Has ability to filter file to pick by extension.

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:flutter_document_picker/flutter_document_picker.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _path = '-';
  bool _pickFileInProgress = false;
  bool _iosPublicDataUTI = true;
  bool _checkByCustomExtension = false;
  bool _checkByMimeType = false;

  final _utiController = TextEditingController(
    text: 'com.sidlatau.example.mwfbak',
  );

  final _extensionController = TextEditingController(
    text: 'mwfbak',
  );

  final _mimeTypeController = TextEditingController(
    text: 'application/pdf image/png',
  );

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
          actions: <Widget>[
            IconButton(
              icon: Icon(Icons.open_in_new),
              onPressed: _pickFileInProgress ? null : _pickDocument,
            )
          ],
        ),
        body: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                  'Picked file path:',
                  style: Theme.of(context).textTheme.title,
                ),
                Text('$_path'),
                _pickFileInProgress ? CircularProgressIndicator() : Container(),
                _buildCommonParams(),
                Theme.of(context).platform == TargetPlatform.iOS
                    ? _buildIOSParams()
                    : _buildAndroidParams(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  _pickDocument() async {
    String result;
    try {
      setState(() {
        _path = '-';
        _pickFileInProgress = true;
      });

      FlutterDocumentPickerParams params = FlutterDocumentPickerParams(
        allowedFileExtensions: _checkByCustomExtension
            ? _extensionController.text
                .split(' ')
                .where((x) => x.isNotEmpty)
                .toList()
            : null,
        allowedUtiTypes: _iosPublicDataUTI
            ? null
            : _utiController.text
                .split(' ')
                .where((x) => x.isNotEmpty)
                .toList(),
        allowedMimeTypes: _checkByMimeType
            ? _mimeTypeController.text
                .split(' ')
                .where((x) => x.isNotEmpty)
                .toList()
            : null,
      );

      result = await FlutterDocumentPicker.openDocument(params: params);
    } catch (e) {
      print(e);
      result = 'Error: $e';
    } finally {
      setState(() {
        _pickFileInProgress = false;
      });
    }

    setState(() {
      _path = result;
    });
  }

  _buildIOSParams() {
    return ParamsCard(
      title: 'iOS Params',
      children: <Widget>[
        Text(
          'Example app is configured to pick custom document type with extension ".mwfbak"',
          style: Theme.of(context).textTheme.body1,
        ),
        Param(
          isEnabled: !_iosPublicDataUTI,
          description:
              'Allow pick all documents("public.data" UTI will be used).',
          controller: _utiController,
          onEnabledChanged: (value) {
            setState(() {
              _iosPublicDataUTI = value;
            });
          },
          textLabel: 'Uniform Type Identifier to pick:',
        ),
      ],
    );
  }

  _buildAndroidParams() {
    return ParamsCard(
      title: 'Android Params',
      children: <Widget>[
        Param(
          isEnabled: _checkByMimeType,
          description: 'Filter files by MIME type',
          controller: _mimeTypeController,
          onEnabledChanged: (value) {
            setState(() {
              _checkByMimeType = value;
            });
          },
          textLabel: 'Allowed MIME types (separated by space):',
        ),
      ],
    );
  }

  _buildCommonParams() {
    return ParamsCard(
      title: 'Common Params',
      children: <Widget>[
        Param(
          isEnabled: _checkByCustomExtension,
          description:
              'Check file by extension - if picked file does not have wantent extension - return "extension_mismatch" error',
          controller: _extensionController,
          onEnabledChanged: (value) {
            setState(() {
              _checkByCustomExtension = value;
            });
          },
          textLabel: 'File extensions (separated by space):',
        ),
      ],
    );
  }
}

class Param extends StatelessWidget {
  final bool isEnabled;
  final ValueChanged<bool> onEnabledChanged;
  final TextEditingController controller;
  final String description;
  final String textLabel;

  Param({
    @required this.isEnabled,
    this.onEnabledChanged,
    this.controller,
    this.description,
    this.textLabel,
  })  : assert(isEnabled != null),
        assert(onEnabledChanged != null),
        assert(description != null),
        assert(textLabel != null),
        assert(controller != null);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Row(
          children: <Widget>[
            Expanded(
              child: Padding(
                padding: const EdgeInsets.only(bottom: 16.0),
                child: Text(
                  description,
                  softWrap: true,
                ),
              ),
            ),
            Checkbox(
              value: isEnabled,
              onChanged: onEnabledChanged,
            ),
          ],
        ),
        TextField(
          controller: controller,
          enabled: isEnabled,
          decoration: InputDecoration(
            border: OutlineInputBorder(),
            labelText: textLabel,
          ),
        ),
      ],
    );
  }
}

class ParamsCard extends StatelessWidget {
  final String title;
  final List<Widget> children;

  ParamsCard({
    @required this.title,
    @required this.children,
  })  : assert(title != null),
        assert(children != null);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.only(top: 24.0),
      child: Card(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.only(bottom: 16.0),
                child: Text(
                  title,
                  style: Theme.of(context).textTheme.headline,
                ),
              ),
            ]..addAll(children),
          ),
        ),
      ),
    );
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  flutter_document_picker: ^4.0.0

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:flutter_document_picker/flutter_document_picker.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
89
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
95
Learn more about scoring.

We analyzed this package on Apr 3, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.7.1
  • pana: 0.13.6
  • Flutter: 1.12.13+hotfix.8

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.11 1.14.12
meta 1.1.8
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8