Flutter外部路径访问插件external_path_ios_mac的使用

Flutter外部路径访问插件external_path_ios_mac的使用

external_path_ios_mac 是一个用于在iOS和macOS设备上恢复目录路径的Flutter包,确保文件访问和管理跨平台一致。

开始使用

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

dependencies:
  external_path_ios_mac: ^0.0.5

或者从GitHub直接引用:

dependencies:
  external_path_ios_mac:
    git:
      url: https://github.com/SwanFlutter/external_path_ios_mac.git

如何使用

导入包

import 'package:external_path_ios_mac/external_path_ios_mac.dart';

支持的iOS目录

- `DIRECTORY_DOWNLOADS`: ExternalPathIosMac.DIRECTORY_DOWNLOADS
- `DIRECTORY_MUSIC`: ExternalPathIosMac.DIRECTORY_MUSIC
- `DIRECTORY_PODCASTS`: ExternalPathIosMac.DIRECTORY_PODCASTS
- `DIRECTORY_RINGTONES`: ExternalPathIosMac.DIRECTORY_RINGTONES
- `DIRECTORY_ALARMS`: ExternalPathIosMac.DIRECTORY_ALARMS
- `DIRECTORY_NOTIFICATIONS`: ExternalPathIosMac.DIRECTORY_NOTIFICATIONS
- `DIRECTORY_PICTURES`: ExternalPathIosMac.DIRECTORY_PICTURES
- `DIRECTORY_MOVIES`: ExternalPathIosMac.DIRECTORY_MOVIES
- `DIRECTORY_DCIM`: ExternalPathIosMac.DIRECTORY_DCIM
- `DIRECTORY_DOCUMENTS`: ExternalPathIosMac.DIRECTORY_DOCUMENTS
- `DIRECTORY_SCREENSHOTS`: ExternalPathIosMac.DIRECTORY_SCREENSHOTS
- `DIRECTORY_AUDIOBOOKS`: ExternalPathIosMac.DIRECTORY_AUDIOBOOKS

支持的macOS目录

- `DIRECTORY_DOWNLOADS`: ExternalPathIosMac.DIRECTORY_DOWNLOADS
- `DIRECTORY_PICTURES`: ExternalPathIosMac.DIRECTORY_PICTURES
- `DIRECTORY_MOVIES`: ExternalPathIosMac.DIRECTORY_MOVIES

iOS权限配置

Info.plist中添加以下键值对:

<key>NSPhotoLibraryUsageDescription</key>
<string>我们需要访问您的照片库以选择图像进行编辑。</string>
<key>NSCameraUsageDescription</key>
<string>我们需要访问您的相机以拍摄照片进行编辑。</string>

macOS安装

由于macOS实现使用了file_selector,因此需要添加文件系统访问权限:

<key>com.apple.security.files.user-selected.read-only</key>
<true/>

完整示例

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:external_path_ios_mac/external_path_ios_mac.dart';

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final _externalPathIosMacPlugin = ExternalPathIosMac();

  String _directoryPathDownload = '';
  String _directoryPathMusic = '';
  String _directoryPathPodcasts = '';
  String _directoryPathRingtones = '';
  String _directoryPathAlarms = '';
  String _directoryPathNotifications = '';
  String _directoryPathPictures = '';
  String _directoryPathMovies = '';
  String _directoryPathDCIM = '';
  String _directoryPathDocuments = '';
  String _directoryPathScreenshots = '';
  String _directoryPathAudiobooks = '';

  // mac path
  String _directoryPathDownloadMac = '';
  String _directoryPathPicturesMac = '';
  String _directoryPathMoviesMac = '';

  String _platformVersion = '';

  [@override](/user/override)
  void initState() {
    super.initState();
    _initPlatformState();
  }

  Future<void> _initPlatformState() async {
    String platformVersion;
    try {
      platformVersion = (await _externalPathIosMacPlugin.getPlatformVersion()) ?? 'Unknown platform version';

      _directoryPathDownload = (await _externalPathIosMacPlugin.getDirectoryPath(directory: ExternalPathIosMac.DIRECTORY_DOWNLOADS)) ?? 'Unknown directory';
      _directoryPathMusic = (await _externalPathIosMacPlugin.getDirectoryPath(directory: ExternalPathIosMac.DIRECTORY_MUSIC)) ?? 'Unknown directory';
      _directoryPathPodcasts = (await _externalPathIosMacPlugin.getDirectoryPath(directory: ExternalPathIosMac.DIRECTORY_PODCASTS)) ?? 'Unknown directory';
      _directoryPathRingtones = (await _externalPathIosMacPlugin.getDirectoryPath(directory: ExternalPathIosMac.DIRECTORY_RINGTONES)) ?? 'Unknown directory';
      _directoryPathAlarms = (await _externalPathIosMacPlugin.getDirectoryPath(directory: ExternalPathIosMac.DIRECTORY_ALARMS)) ?? 'Unknown directory';
      _directoryPathNotifications = (await _externalPathIosMacPlugin.getDirectoryPath(directory: ExternalPathIosMac.DIRECTORY_NOTIFICATIONS)) ?? 'Unknown directory';
      _directoryPathPictures = (await _externalPathIosMacPlugin.getDirectoryPath(directory: ExternalPathIosMac.DIRECTORY_PICTURES)) ?? 'Unknown directory';
      _directoryPathMovies = (await _externalPathIosMacPlugin.getDirectoryPath(directory: ExternalPathIosMac.DIRECTORY_MOVIES)) ?? 'Unknown directory';
      _directoryPathDCIM = (await _externalPathIosMacPlugin.getDirectoryPath(directory: ExternalPathIosMac.DIRECTORY_DCIM)) ?? 'Unknown directory';
      _directoryPathDocuments = (await _externalPathIosMacPlugin.getDirectoryPath(directory: ExternalPathIosMac.DIRECTORY_DOCUMENTS)) ?? 'Unknown directory';
      _directoryPathScreenshots = (await _externalPathIosMacPlugin.getDirectoryPath(directory: ExternalPathIosMac.DIRECTORY_SCREENSHOTS)) ?? 'Unknown directory';
      _directoryPathAudiobooks = (await _externalPathIosMacPlugin.getDirectoryPath(directory: ExternalPathIosMac.DIRECTORY_AUDIOBOOKS)) ?? 'Unknown directory';

      // get path mac
      _directoryPathDownloadMac = (await _externalPathIosMacPlugin.getDirectoryPathMacOs(directory: ExternalPathIosMac.DIRECTORY_DOWNLOADS_MAC)) ?? 'Unknown directory';
      _directoryPathPicturesMac = (await _externalPathIosMacPlugin.getDirectoryPathMacOs(directory: ExternalPathIosMac.DIRECTORY_PICTURES_MAC)) ?? 'Unknown directory';
      _directoryPathMoviesMac = (await _externalPathIosMacPlugin.getDirectoryPathMacOs(directory: ExternalPathIosMac.DIRECTORY_MOVIES_MAC)) ?? 'Unknown directory';

    } catch (e) {
      platformVersion = 'Failed to get platform version.';
    }

    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  Future<void> _saveFile() async {
    List<String> directoryPaths = [
      _directoryPathDownload,
      _directoryPathMusic,
      _directoryPathPodcasts,
      _directoryPathRingtones,
      _directoryPathAlarms,
      _directoryPathNotifications,
      _directoryPathPictures,
      _directoryPathMovies,
      _directoryPathDCIM,
      _directoryPathDocuments,
      _directoryPathScreenshots,
      _directoryPathAudiobooks,
      _directoryPathDownloadMac,
      _directoryPathPicturesMac,
      _directoryPathMoviesMac,
    ];

    try {
      const fileName = 'example.txt';
      for (String path in directoryPaths) {
        if (path != 'Unknown directory' && path.isNotEmpty) {
          final filePath = '$path/$fileName';
          final file = File(filePath);
          await file.writeAsString('This is a sample text.');

          ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('File saved to $filePath')));
        }
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Failed to save file: $e')));
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('插件示例应用'),
        ),
        body: Center(
          child: SingleChildScrollView(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text('运行于: $_platformVersion'),
                const SizedBox(height: 5),
                Text('_directoryPathDownload: $_directoryPathDownload'),
                const SizedBox(height: 5),
                Text('_directoryPathMusic: $_directoryPathMusic'),
                const SizedBox(height: 5),
                Text('_directoryPathPodcasts: $_directoryPathPodcasts'),
                const SizedBox(height: 5),
                Text('_directoryPathRingtones: $_directoryPathRingtones'),
                const SizedBox(height: 5),
                Text('_directoryPathAlarms: $_directoryPathAlarms'),
                const SizedBox(height: 5),
                Text('_directoryPathNotifications: $_directoryPathNotifications'),
                const SizedBox(height: 5),
                Text('_directoryPathPictures: $_directoryPathPictures'),
                const SizedBox(height: 5),
                Text('_directoryPathMovies: $_directoryPathMovies'),
                const SizedBox(height: 5),
                Text('_directoryPathDCIM: $_directoryPathDCIM'),
                const SizedBox(height: 5),
                Text('_directoryPathDocuments: $_directoryPathDocuments'),
                const SizedBox(height: 5),
                Text('_directoryPathScreenshots: $_directoryPathScreenshots'),
                const SizedBox(height: 5),
                Text('_directoryPathAudiobooks: $_directoryPathAudiobooks'),
                const SizedBox(height: 5),
                // mac
                Text('_directoryPathDownloadMac: $_directoryPathDownloadMac'),
                const SizedBox(height: 5),
                Text('_directoryPathPicturesMac: $_directoryPathPicturesMac'),
                const SizedBox(height: 5),
                Text('_directoryPathMoviesMac: $_directoryPathMoviesMac'),
                //
                ElevatedButton(
                  onPressed: _saveFile,
                  child: const Text('保存文件'),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

更多关于Flutter外部路径访问插件external_path_ios_mac的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter外部路径访问插件external_path_ios_mac的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用external_path_ios_mac插件来访问外部路径的示例代码。external_path_ios_mac插件允许你在iOS和macOS平台上访问和操作文件系统中的特定路径。

步骤 1: 添加依赖

首先,在你的pubspec.yaml文件中添加external_path_ios_mac依赖:

dependencies:
  flutter:
    sdk: flutter
  external_path_ios_mac: ^x.y.z  # 请替换为最新版本号

然后运行flutter pub get来安装依赖。

步骤 2: 配置权限

在iOS和macOS上访问外部路径可能需要适当的权限配置。确保在Info.plist文件中添加必要的权限声明(如果需要)。

步骤 3: 使用插件

下面是一个简单的示例,演示如何使用external_path_ios_mac插件来访问一个外部路径并读取其中的文件内容。

import 'package:flutter/material.dart';
import 'package:external_path_ios_mac/external_path_ios_mac.dart';
import 'dart:io';

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

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

class _MyAppState extends State<MyApp> {
  String? fileContent;

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

  Future<void> _readFileFromExternalPath() async {
    // 示例路径,这里使用Documents目录作为外部路径
    String directoryPath = await ExternalPath.documentsDirectory;
    String filePath = '$directoryPath/example.txt';

    try {
      File file = File(filePath);
      if (await file.exists()) {
        String contents = await file.readAsString();
        setState(() {
          fileContent = contents;
        });
      } else {
        setState(() {
          fileContent = 'File does not exist.';
        });
      }
    } catch (e) {
      setState(() {
        fileContent = 'Error reading file: $e';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('External Path Example'),
        ),
        body: Center(
          child: Text(fileContent ?? 'Loading...'),
        ),
      ),
    );
  }
}

注意事项

  1. 路径选择:在示例中,我们使用了ExternalPath.documentsDirectory来获取Documents目录的路径。你可以根据需要选择其他目录,例如ExternalPath.cachesDirectoryExternalPath.libraryDirectory等。

  2. 文件操作external_path_ios_mac插件本身不提供文件操作功能,但你可以结合Dart的dart:io库来执行文件读写操作。

  3. 错误处理:在实际应用中,务必添加适当的错误处理逻辑,以应对文件不存在、权限不足等情况。

  4. 平台特定代码:虽然external_path_ios_mac主要针对iOS和macOS,但你可以在Flutter项目中结合其他插件(如path_provider)来实现跨平台文件访问。

通过上述步骤,你可以在Flutter项目中成功使用external_path_ios_mac插件来访问外部路径并操作文件。

回到顶部