Flutter项目中如何加载位于frameworks下的dylib文件

在Flutter项目中,如何正确加载位于frameworks目录下的dylib文件?我已经将dylib文件放在iOS项目的frameworks文件夹中,但在运行时仍然提示找不到库。是否需要修改Podfile或Xcode的Build Settings?具体应该如何配置才能确保Flutter能正确识别并加载这些动态库?

2 回复

在Flutter项目中使用DynamicLibrary.open加载dylib文件。例如:

import 'dart:ffi';

final dylib = DynamicLibrary.open('frameworks/your_library.dylib');

确保dylib文件已正确添加到项目框架目录中。

更多关于Flutter项目中如何加载位于frameworks下的dylib文件的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在 Flutter 项目中加载位于 frameworks 目录下的 .dylib 文件,可以通过以下步骤实现:

1. 将 .dylib 文件添加到项目中

  • 在 Flutter 项目的 ios 目录下,将 .dylib 文件放入 Runner/Frameworks 文件夹中(如不存在需手动创建)。
  • 在 Xcode 中,右键点击 RunnerAdd Files to "Runner",选择添加 .dylib 文件,并确保勾选 “Copy items if needed”。

2. 配置 Xcode

  • 在 Xcode 中选中 Runner 目标,进入 General 标签页,在 Frameworks, Libraries, and Embedded Content 部分添加 .dylib 文件,并设置为 Embed & Sign

3. 在 Dart 代码中通过平台通道调用

由于 Flutter 无法直接加载原生库,需通过平台通道(MethodChannel)调用 iOS 原生代码来使用 .dylib 功能。

Dart 端示例代码:

import 'package:flutter/services.dart';

final MethodChannel _channel = MethodChannel('native_lib_channel');

Future<void> loadAndUseDylib() async {
  try {
    final String result = await _channel.invokeMethod('callDylibFunction');
    print('Dylib result: $result');
  } on PlatformException catch (e) {
    print("Failed: '${e.message}'.");
  }
}

iOS 端(Swift)示例代码:ios/Runner/AppDelegate.swift 中添加:

import Flutter
import UIKit

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
    let channel = FlutterMethodChannel(name: "native_lib_channel", binaryMessenger: controller.binaryMessenger)
    
    channel.setMethodCallHandler { (call, result) in
      if call.method == "callDylibFunction" {
        // 调用 dylib 中的函数
        self.callDylibFunction(result: result)
      } else {
        result(FlutterMethodNotImplemented)
      }
    }
    
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
  
  private func callDylibFunction(result: FlutterResult) {
    // 加载 dylib 并调用函数
    guard let libHandle = dlopen("YourLibrary.dylib", RTLD_NOW) else {
      result(FlutterError(code: "UNAVAILABLE", message: "Failed to load dylib", details: nil))
      return
    }
    
    // 获取函数指针(替换 YourFunctionName 为实际函数名)
    typealias FunctionType = @convention(c) () -> UnsafePointer<CChar>?
    let symbol = dlsym(libHandle, "YourFunctionName")
    if symbol == nil {
      result(FlutterError(code: "UNAVAILABLE", message: "Function not found", details: nil))
      return
    }
    
    let function = unsafeBitCast(symbol, to: FunctionType.self)
    if let output = function() {
      result(String(cString: output))
    } else {
      result(FlutterError(code: "ERROR", message: "Function call failed", details: nil))
    }
    
    dlclose(libHandle)
  }
}

注意事项:

  • 确保 .dylib 文件与当前 iOS 架构兼容(如 arm64)。
  • .dylib 依赖其他库,需一并添加到项目中。
  • 使用 dlopendlsym 时注意函数签名匹配。

通过以上步骤,即可在 Flutter 项目中加载并使用 frameworks 目录下的 .dylib 文件。

回到顶部