Flutter文件打开功能插件fl_open_file的使用

Flutter文件打开功能插件fl_open_file的使用

概述

fl_open_file 是一个用于在 Flutter 中调用原生应用打开文件的插件,支持多种平台,包括 iOS(通过 DocumentInteraction)、Android(通过 Intent)、PC(通过 FFI)和 Web(通过 dart:html)。

使用方法

添加依赖

pubspec.yaml 文件中添加 fl_open_file 插件作为依赖项。例如:

dependencies:
  fl_open_file: ^lastVersion

注意:确保使用最新版本号。

请求权限(从 3.3.0 开始)

如果你需要打开外部文件,请确保在 Android 上请求权限。这是一个示例代码:

import 'package:fl_open_file/fl_open_file.dart';

void openExternalFile() async {
  final result = await OpenFile.open("/sdcard/example.txt");
  print("File opened with status: ${result.type}");
}

示例代码

以下是一个完整的示例代码,展示了如何使用 fl_open_file 插件来打开文件:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('fl_open_file 示例')),
        body: Center(
          child: ElevatedButton(
            onPressed: () async {
              // 打开文件
              final result = await OpenFile.open("/sdcard/example.txt");

              // 打印结果状态
              print("文件打开状态: ${result.type}, 消息: ${result.message}");
            },
            child: Text('打开文件'),
          ),
        ),
      ),
    );
  }
}

支持的文件类型

Android

以下是 Android 平台支持的文件类型映射表:

{
  ".3gp": "video/3gpp",
  ".torrent": "application/x-bittorrent",
  ".kml": "application/vnd.google-earth.kml+xml",
  ".gpx": "application/gpx+xml",
  ".csv": "application/vnd.ms-excel",
  ".apk": "application/vnd.android.package-archive",
  ".asf": "video/x-ms-asf",
  ".avi": "video/x-msvideo",
  ".bin": "application/octet-stream",
  ".bmp": "image/bmp",
  ".c": "text/plain",
  ".class": "application/octet-stream",
  ".conf": "text/plain",
  ".cpp": "text/plain",
  ".doc": "application/msword",
  ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  ".xls": "application/vnd.ms-excel",
  ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  ".exe": "application/octet-stream",
  ".gif": "image/gif",
  ".gtar": "application/x-gtar",
  ".gz": "application/x-gzip",
  ".h": "text/plain",
  ".htm": "text/html",
  ".html": "text/html",
  ".jar": "application/java-archive",
  ".java": "text/plain",
  ".jpeg": "image/jpeg",
  ".jpg": "image/jpeg",
  ".js": "application/x-javascript",
  ".log": "text/plain",
  ".m3u": "audio/x-mpegurl",
  ".m4a": "audio/mp4a-latm",
  ".m4b": "audio/mp4a-latm",
  ".m4p": "audio/mp4a-latm",
  ".m4u": "video/vnd.mpegurl",
  ".m4v": "video/x-m4v",
  ".mov": "video/quicktime",
  ".mp2": "audio/x-mpeg",
  ".mp3": "audio/x-mpeg",
  ".mp4": "video/mp4",
  ".mpc": "application/vnd.mpohun.certificate",
  ".mpe": "video/mpeg",
  ".mpeg": "video/mpeg",
  ".mpg": "video/mpeg",
  ".mpg4": "video/mp4",
  ".mpga": "audio/mpeg",
  ".msg": "application/vnd.ms-outlook",
  ".ogg": "audio/ogg",
  ".pdf": "application/pdf",
  ".png": "image/png",
  ".pps": "application/vnd.ms-powerpoint",
  ".ppt": "application/vnd.ms-powerpoint",
  ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
  ".prop": "text/plain",
  ".rc": "text/plain",
  ".rmvb": "audio/x-pn-realaudio",
  ".rtf": "application/rtf",
  ".sh": "text/plain",
  ".tar": "application/x-tar",
  ".tgz": "application/x-compressed",
  ".txt": "text/plain",
  ".wav": "audio/x-wav",
  ".wma": "audio/x-ms-wma",
  ".wmv": "audio/x-ms-wmv",
  ".wps": "application/vnd.ms-works",
  ".xml": "text/plain",
  ".z": "application/x-compress",
  ".zip": "application/x-zip-compressed",
  "": "*/*"
}

iOS

以下是 iOS 平台支持的文件类型映射表:

{
  ".rtf": "public.rtf",
  ".txt": "public.plain-text",
  ".html": "public.html",
  ".htm": "public.html",
  ".xml": "public.xml",
  ".tar": "public.tar-archive",
  ".gz": "org.gnu.gnu-zip-archive",
  ".gzip": "org.gnu.gnu-zip-archive",
  ".tgz": "org.gnu.gnu-zip-tar-archive",
  ".jpg": "public.jpeg",
  ".jpeg": "public.jpeg",
  ".png": "public.png",
  ".avi": "public.avi",
  ".mpg": "public.mpeg",
  ".mpeg": "public.mpeg",
  ".mp4": "public.mpeg-4",
  ".3gpp": "public.3gpp",
  ".3gp": "public.3gpp",
  ".mp3": "public.mp3",
  ".zip": "com.pkware.zip-archive",
  ".gif": "com.compuserve.gif",
  ".bmp": "com.microsoft.bmp",
  ".ico": "com.microsoft.ico",
  ".doc": "com.microsoft.word.doc",
  ".xls": "com.microsoft.excel.xls",
  ".ppt": "com.microsoft.powerpoint.​ppt",
  ".wav": "com.microsoft.waveform-​audio",
  ".wm": "com.microsoft.windows-​media-wm",
  ".wmv": "com.microsoft.windows-​media-wmv",
  ".pdf": "com.adobe.pdf"
}

解决冲突问题

Android 的 FileProvider 配置

如果遇到其他插件与 FileProvider 冲突的情况,可以在 AndroidManifest.xml 文件中添加以下配置:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
          package="xxx.xxx.xxxxx">
    <application>
        ...
        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.fileProvider"
            android:exported="false"
            android:grantUriPermissions="true"
            tools:replace="android:authorities">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/filepaths"
                tools:replace="android:resource" />
        </provider>
    </application>
</manifest>

同时,在 res/xml/filepaths.xml 文件中添加以下内容:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <external-path name="external_storage_directory" path="." />
</resources>

Android 的支持库版本冲突

如果遇到 com.android.support:appcompat-v7 版本冲突问题,可以在 /android/build.gradle 文件中添加以下代码:

subprojects {
    project.configurations.all {
        resolutionStrategy.eachDependency { details ->
            if (details.requested.group == 'com.android.support'
                    && !details.requested.name.contains('multidex') ) {
                details.useVersion "27.1.1"
            }
        }
    }
}

更多关于Flutter文件打开功能插件fl_open_file的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter文件打开功能插件fl_open_file的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


fl_open_file 是一个用于在 Flutter 应用中打开文件的插件。它支持打开多种类型的文件,包括图片、文档、音频、视频等,并且可以调用系统默认的应用程序来打开文件。以下是使用 fl_open_file 插件的基本步骤:

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 fl_open_file 依赖:

dependencies:
  flutter:
    sdk: flutter
  fl_open_file: ^1.0.0

然后运行 flutter pub get 来获取依赖。

2. 导入包

在需要使用 fl_open_file 的 Dart 文件中导入包:

import 'package:fl_open_file/fl_open_file.dart';

3. 使用 fl_open_file 打开文件

你可以使用 FlOpenFile.open 方法来打开文件。这个方法需要一个文件路径作为参数。

void openFile(String filePath) async {
  try {
    await FlOpenFile.open(filePath);
  } catch (e) {
    print("无法打开文件: $e");
  }
}

4. 示例

以下是一个完整的示例,展示如何使用 fl_open_file 打开一个文件:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter 文件打开示例'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: () {
              // 替换为你想要打开的文件路径
              String filePath = '/storage/emulated/0/Download/example.pdf';
              openFile(filePath);
            },
            child: Text('打开文件'),
          ),
        ),
      ),
    );
  }
}

void openFile(String filePath) async {
  try {
    await FlOpenFile.open(filePath);
  } catch (e) {
    print("无法打开文件: $e");
  }
}

5. 权限配置(Android)

在 Android 上,你可能需要请求文件访问权限。确保在 AndroidManifest.xml 中添加以下权限:

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

并且在运行时请求这些权限。

6. 权限配置(iOS)

在 iOS 上,你需要在 Info.plist 中添加以下键值对,以允许访问文件系统:

<key>NSDocumentsFolderUsageDescription</key>
<string>需要访问文件系统来打开文件</string>
<key>NSDownloadsFolderUsageDescription</key>
<string>需要访问文件系统来打开文件</string>
回到顶部