Flutter文件打开无需请求安装插件open_file_no_request_install的使用

Flutter文件打开无需请求安装插件open_file_no_request_install的使用


插件简介

open_file_no_request_install 是一个可以在 Flutter 中调用原生应用打开文件的插件,支持以下平台:

  • iOS(通过 DocumentInteraction)
  • Android(通过 Intent)
  • PC(通过 FFI)
  • Web(通过 dart:html)

该插件无需用户手动安装其他应用即可直接打开文件。


使用方法

要使用此插件,请在 pubspec.yaml 文件中添加依赖:

dependencies:
  open_file_no_request_install: ^lastVersion

运行 flutter pub get 更新依赖。


示例代码

以下是一个完整的示例代码,展示如何使用 open_file_no_request_install 插件打开文件。

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

import 'package:open_file_no_request_install/open_file_no_request_install.dart';

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

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

class _MyAppState extends State<MyApp> {
  // 记录文件打开结果
  String _openResult = '未知';

  // 打开文件的方法
  Future<void> openFile() async {
    // 文件路径(根据实际设备调整路径)
    final filePath = '/storage/emulated/0/update.apk';

    // 调用插件打开文件
    final result = await OpenFile.open(filePath);

    // 更新 UI
    setState(() {
      _openResult = "类型=${result.type}  消息=${result.message}";
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('插件示例'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text('打开结果: $_openResult\n'), // 显示打开结果
              TextButton(
                child: Text('点击打开文件'),
                onPressed: openFile, // 点击按钮触发文件打开
              ),
            ],
          ),
        ),
      ),
    );
  }
}

支持的文件类型

Android 平台支持的文件类型
{
    ".3gp": "video/3gpp",
    ".torrent": "application/x-bittorrent",
    ".kml": "application/vnd.google-earth.kml+xml",
    ".gpx": "application/gpx+xml",
    ".csv": "application/vnd.ms-excel",
    ".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 平台支持的文件类型
{
    ".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 的冲突),请在 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>

如果遇到版本冲突问题,请在 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"
            }
        }
    }
}
1 回复

更多关于Flutter文件打开无需请求安装插件open_file_no_request_install的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在 Flutter 中,open_file_no_request_install 是一个用于打开文件(如 PDF、图片、文档等)的插件,它不需要请求用户安装额外的应用程序。这个插件的主要优势是它可以直接调用系统默认的应用程序来打开文件,而不需要用户手动安装其他应用程序。

安装插件

首先,你需要在 pubspec.yaml 文件中添加 open_file_no_request_install 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  open_file_no_request_install: ^1.0.0  # 请确保使用最新版本

然后运行 flutter pub get 来安装插件。

使用插件

在你的 Dart 文件中,导入插件并调用 OpenFileNoRequestInstall.open 方法来打开文件。以下是一个简单的示例:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Open File Example'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: () async {
              // 文件路径
              String filePath = '/storage/emulated/0/Download/example.pdf';

              // 打开文件
              try {
                await OpenFileNoRequestInstall.open(filePath);
              } catch (e) {
                print('Error opening file: $e');
              }
            },
            child: Text('Open PDF'),
          ),
        ),
      ),
    );
  }
}

注意事项

  1. 文件路径: 你需要确保文件路径是正确的,并且应用程序有权访问该路径。在 Android 上,你可能需要请求存储权限。

  2. 文件类型: 插件会根据文件扩展名自动调用系统默认的应用程序来打开文件。确保文件扩展名正确。

  3. 错误处理: 如果文件无法打开,插件会抛出异常,因此建议在调用 open 方法时进行错误处理。

  4. 平台支持: 该插件支持 Android 和 iOS 平台,但在不同平台上可能会有不同的行为。

权限处理(Android)

在 Android 上,如果你要访问外部存储(如 /storage/emulated/0/),你可能需要请求 READ_EXTERNAL_STORAGE 权限。你可以在 AndroidManifest.xml 中添加以下权限:

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

并且在运行时请求权限:

import 'package:permission_handler/permission_handler.dart';

void requestPermission() async {
  var status = await Permission.storage.status;
  if (!status.isGranted) {
    await Permission.storage.request();
  }
}
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!