Flutter应用组目录管理插件app_group_directory的使用

发布于 1周前 作者 vueper 来自 Flutter

Flutter应用组目录管理插件app_group_directory的使用

插件简介

pub package build status

app_group_directory 是一个Flutter插件,允许访问iOS上的共享应用程序组容器。在iOS上,它使用 NSFileManagercontainerURLForSecurityApplicationGroupIdentifier API 来获取应用组容器的URL。

ios_app_group包迁移

如果您之前使用的是ios_app_group包,则需要进行以下更改以迁移到app_group_directory

  • package:ios_app_group/ios_app_group.dart的导入更改为package:app_group_directory/app_group_directory.dart
  • pubspec.yaml中将ios_app_group:依赖项更改为app_group_directory: ^2.0.0
  • IosAppGroup类引用更改为AppGroupDirectory

使用方法

下面是一个简单的示例代码,展示了如何使用app_group_directory插件来获取共享的应用程序组目录:

import 'dart:io';

import 'package:app_group_directory/app_group_directory.dart';

void main() async {
  Directory? sharedDirectory = await AppGroupDirectory.getAppGroupDirectory('com.example.app');
  print('Shared directory: ${sharedDirectory?.path}');
}

完整示例Demo

下面是一个完整的Flutter应用程序示例,演示了如何在应用程序中使用app_group_directory插件:

import 'dart:async';
import 'dart:io';

import 'package:app_group_directory/app_group_directory.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

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

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

class _MyAppState extends State<MyApp> {
  String _sharedDirectory = 'Unknown';

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

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    Directory? sharedDirectory;
    // Platform messages may fail, so we use a try/catch PlatformException.

    try {
      sharedDirectory = await AppGroupDirectory.getAppGroupDirectory(
          'com.github.mingchen.test');
      debugPrint('getAppGroupDirectory: $sharedDirectory');
    } on PlatformException catch (ex) {
      debugPrint('Failed to call native method: $ex');
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _sharedDirectory = sharedDirectory.toString();
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Text('Shared directory: $_sharedDirectory\n'),
        ),
      ),
    );
  }
}

这个示例应用程序启动时会尝试获取指定的应用程序组目录,并在界面上显示该目录的路径。如果获取失败或遇到任何问题,它会捕获异常并在调试控制台中打印错误信息。

希望这些信息对您有所帮助!如果您有任何问题或需要进一步的帮助,请随时提问。


更多关于Flutter应用组目录管理插件app_group_directory的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter应用组目录管理插件app_group_directory的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter应用中使用app_group_directory插件进行组目录管理的示例代码。这个插件允许你在不同的iOS和Android应用之间共享文件。

首先,确保你已经在pubspec.yaml文件中添加了app_group_directory依赖:

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

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

iOS配置

在iOS上,你需要配置应用组。打开ios/Runner/AppDelegate.swift文件,并添加以下代码来设置应用组:

import UIKit
import Flutter
import app_group_directory

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)
    
    // 设置应用组标识符
    let appGroupIdentifier = "group.com.yourcompany.yourappgroup"
    UserDefaults(suiteName: appGroupIdentifier)?.synchronize()
    
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

确保在Xcode中启用应用组,并在Capabilities标签页中添加你的应用组标识符。

Android配置

在Android上,你需要在AndroidManifest.xml中配置文件共享:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.yourcompany.yourapp">

    <application
        ... >
        
        <!-- 声明文件提供者 -->
        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>
        
        ...
    </application>
</manifest>

然后在res/xml/file_paths.xml文件中配置文件路径(如果文件路径文件不存在,请创建它):

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>

此外,你需要在build.gradle文件中配置签名和应用组标识符(如果需要):

android {
    ...
    defaultConfig {
        ...
        applicationId "com.yourcompany.yourapp"
        ...
        // 配置签名
        signingConfigs {
            release {
                ...
            }
        }
        buildTypes {
            release {
                signingConfig signingConfigs.release
                ...
            }
        }
    }
    ...
}

Flutter代码示例

以下是一个Flutter代码示例,演示如何使用app_group_directory插件进行文件读写操作:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('App Group Directory Example'),
        ),
        body: Center(
          child: MyHomePage(),
        ),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String? fileContent;

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

  Future<void> _writeFile(String content) async {
    try {
      String? appGroupId = await AppGroupDirectory.getAppGroupId();
      if (appGroupId == null) {
        throw Exception("App Group ID not found");
      }

      File file = File("${AppGroupDirectory.getDirectory(appGroupId)!}/example.txt");
      await file.writeAsString(content);
      print("File written successfully");

      setState(() {
        fileContent = null; // Clear the current content to reflect the new file state
      });

      // Re-read the file to update the UI
      _readFile();
    } catch (e) {
      print("Error writing file: $e");
    }
  }

  Future<void> _readFile() async {
    try {
      String? appGroupId = await AppGroupDirectory.getAppGroupId();
      if (appGroupId == null) {
        throw Exception("App Group ID not found");
      }

      File file = File("${AppGroupDirectory.getDirectory(appGroupId)!}/example.txt");
      if (await file.exists()) {
        String content = await file.readAsString();
        setState(() {
          fileContent = content;
        });
      } else {
        setState(() {
          fileContent = "File does not exist";
        });
      }
    } catch (e) {
      print("Error reading file: $e");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Text(
          "File Content:",
          style: TextStyle(fontSize: 20),
        ),
        SizedBox(height: 10),
        Text(
          fileContent ?? "Loading...",
          style: TextStyle(fontSize: 18),
        ),
        SizedBox(height: 20),
        ElevatedButton(
          onPressed: () => _writeFile("Hello, App Group Directory!"),
          child: Text("Write to File"),
        ),
      ],
    );
  }
}

在这个示例中,我们演示了如何使用app_group_directory插件读取和写入共享文件。请注意,这个插件的使用可能因平台而异,因此务必在iOS和Android上都进行测试。

回到顶部