Flutter如何与Rust进行交互
我最近在学习Flutter开发,想用Rust来实现一些高性能的计算模块。请问应该如何实现Flutter与Rust之间的交互?具体有哪些可行的方案?需要用到哪些工具或库?能否提供一个简单的示例代码说明基本的调用流程?另外,这种跨语言交互在性能上会有什么影响吗?
2 回复
Flutter可通过FFI直接调用Rust编译的C ABI动态库。步骤:
- Rust用
#[no_mangle]和extern "C"导出函数 - 编译为
.so/.dylib/.dll - Flutter用
dart:ffi加载动态库并调用函数
也可用第三方库如flutter_rust_bridge简化流程。
更多关于Flutter如何与Rust进行交互的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
Flutter 与 Rust 交互主要通过 FFI(Foreign Function Interface) 实现,适用于高性能计算、加密或复用现有 Rust 库的场景。以下是核心步骤和示例:
1. 创建 Rust 动态库
- 使用
cdylib编译目标生成.so(Linux)、.dylib(macOS)或.dll(Windows)。 - 示例
Cargo.toml:[lib] crate-type = ["cdylib"] [dependencies] - Rust 代码示例(
src/lib.rs):#[no_mangle] pub extern "C" fn add(a: i32, b: i32) -> i32 { a + b } - 编译命令:
cargo build --release
2. 在 Flutter 中集成动态库
- 将生成的动态库(如
libexample.so)放入 Flutter 项目的android/src/main/jniLibs/(Android)或ios/Runner/(iOS)。 - 添加
ffi依赖(pubspec.yaml):dependencies: ffi: ^2.0.1
3. 通过 Dart FFI 调用 Rust 函数
- Dart 代码示例:
import 'dart:ffi'; import 'package:ffi/ffi.dart'; // 加载动态库(路径需根据平台调整) final DynamicLibrary nativeLib = Platform.isAndroid ? DynamicLibrary.open('libexample.so') : DynamicLibrary.process(); // 定义 FFI 绑定 typedef AddFunc = Int32 Function(Int32, Int32); typedef Add = int Function(int, int); final Add add = nativeLib .lookup<NativeFunction<AddFunc>>('add') .asFunction<Add>(); // 调用函数 void main() { print('3 + 5 = ${add(3, 5)}'); // 输出:3 + 5 = 8 }
4. 复杂数据类型处理
- 使用
ffi的Pointer和Struct处理字符串或结构体:#[no_mangle] pub extern "C" fn greet(name: *const c_char) -> *mut c_char { let name_str = unsafe { CStr::from_ptr(name).to_str().unwrap() }; format!("Hello, {}!", name_str).into_c_string().into_raw() }// Dart 侧需手动管理内存(使用 `malloc` 和 `free`)
注意事项
- 内存管理:Rust 返回的指针需在 Dart 中显式释放(如调用
malloc.free)。 - 跨平台构建:需为 Android(ARM/x86)和 iOS(ARM64)分别编译 Rust 库。
- 异步调用:复杂操作建议通过
Isolate避免阻塞 UI 线程。
替代方案
- flutter_rust_bridge:自动化生成绑定代码,简化复杂数据传递。
通过上述方法,可高效结合 Flutter 的跨平台 UI 与 Rust 的性能优势。

