使用flutter_rust_bridge为dart构建第三方包

1. 新建插件项目

注意: hello_rust_ffi_plugin 改成插件项目名字

bash 复制代码
flutter create --template=plugin_ffi hello_rust_ffi_plugin --platforms android,ios,macos,windows,linux

2. 添加cargokit自动编译脚本

注意: hello_rust_ffi_plugin 修改插件名

sql 复制代码
cd hello_rust_ffi_plugin
git init
git add --all
git commit -m "initial commit"

添加cargokit 到插件目录树

bash 复制代码
git subtree add --prefix cargokit https://github.com/irondash/cargokit.git main --squash

3.添加rust项目

注意: 修改hello_rust_ffi_plugin项目名字

bash 复制代码
cargo new rust --lib --name hello_rust_ffi_plugin

这个命令会在插件的项目目录下添加一个rust目录,需要在里面编写rust代码

打开rust/cargo.toml文件新增这些内容,不加会构建lib失败,注意单词拼写

toml 复制代码
## >>>>>>>>>>>>> ADDED CODE >>>>>>>>>>>>>
[lib]
crate-type = ["cdylib", "staticlib"]
## <<<<<<<<<<<< ADDED CODE <<<<<<<<<<<<

修改后完整内容如下

toml 复制代码
[package]
name = "hello_rust_ffi_plugin"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
crate-type = ["cdylib", "staticlib"]

4. 添加编译脚本

1. macos编译脚本

修改这个文件 添加这些内容

⚠️注意修改替换插件名字

修改后的内容如下

podspec 复制代码
#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html.
# Run `pod lib lint hello_rust_ffi_plugin.podspec` to validate before publishing.
#
Pod::Spec.new do |s|
  s.name             = 'hello_rust_ffi_plugin'
  s.version          = '0.0.1'
  s.summary          = 'A new Flutter FFI plugin project.'
  s.description      = <<-DESC
A new Flutter FFI plugin project.
                       DESC
  s.homepage         = 'http://example.com'
  s.license          = { :file => '../LICENSE' }
  s.author           = { 'Your Company' => 'email@example.com' }

  # This will ensure the source files in Classes/ are included in the native
  # builds of apps using this FFI plugin. Podspec does not support relative
  # paths, so Classes contains a forwarder C file that relatively imports
  # `../src/*` so that the C sources can be shared among all target platforms.
  s.source           = { :path => '.' }
  s.source_files     = 'Classes/**/*'
  s.dependency 'FlutterMacOS'

  s.platform = :osx, '10.11'
  s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' }
  s.swift_version = '5.0'


  s.script_phase = {
    :name => 'Build Rust library',
    # First argument is relative path to the `rust` folder, second is name of rust library
    :script => 'sh "$PODS_TARGET_SRCROOT/../cargokit/build_pod.sh" ../rust hello_rust_ffi_plugin',
    :execution_position => :before_compile,
    :input_files => ['${BUILT_PRODUCTS_DIR}/cargokit_phony'],
    # Let XCode know that the static library referenced in -force_load below is
    # created by this build step.
    :output_files => ["${BUILT_PRODUCTS_DIR}/libhello_rust_ffi_plugin.a"],
  }
  s.pod_target_xcconfig = {
    'DEFINES_MODULE' => 'YES',
    # Flutter.framework does not contain a i386 slice.
    'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386',
    'OTHER_LDFLAGS' => '-force_load ${BUILT_PRODUCTS_DIR}/libhello_rust_ffi_plugin.a',
  }
end

2. iOS基本和macos一样,可以改为软连接

执行命令

bash 复制代码
rm -R ios
ln -s macos ios

3. Windows和Linux

都是一样的,复制就行,注意修改替换插件名字

txt 复制代码
# The Flutter tooling requires that developers have CMake 3.10 or later
# installed. You should not increase this version, as doing so will cause
# the plugin to fail to compile for some customers of the plugin.
cmake_minimum_required(VERSION 3.10)

# Project-level configuration.
set(PROJECT_NAME "hello_rust_ffi_plugin")
project(${PROJECT_NAME} LANGUAGES CXX)

# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# Replace add_subdirectory that references old C++ code with Cargokit:
include("../cargokit/cmake/cargokit.cmake")
apply_cargokit(${PROJECT_NAME} ../rust hello_rust_ffi_plugin "")
# <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

# List of absolute paths to libraries that should be bundled with the plugin.
# This list could contain prebuilt libraries, or libraries created by an
# external build triggered from this build file.
set(hello_rust_ffi_plugin_bundled_libraries
  # Defined in ../src/CMakeLists.txt.
  # This can be changed to accommodate different builds.

  # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
  # Replace original target file with the one produced by Cargokit:
  "${${PROJECT_NAME}_cargokit_lib}"
  # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  PARENT_SCOPE
)

4.Android

android/build.gradle修改如下内容

注意修改插件名

gradle 复制代码
group 'com.example.hello_ffi_plugin'
version '1.0'

buildscript {
    repositories {
        google()
        mavenCentral()
    }

    dependencies {
        // The Android Gradle Plugin knows how to build native code with the NDK.
        classpath 'com.android.tools.build:gradle:7.3.0'
    }
}

rootProject.allprojects {
    repositories {
        google()
        mavenCentral()
    }
}

apply plugin: 'com.android.library'

android {
    if (project.android.hasProperty("namespace")) {
        namespace 'com.example.hello_ffi_plugin'
    }

    // Bumping the plugin compileSdkVersion requires all clients of this plugin
    // to bump the version in their app.
    compileSdkVersion 33

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        minSdkVersion 19
    }
}

// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

apply from: "../cargokit/gradle/plugin.gradle"

cargokit {
    manifestDir = "../rust"
    libname = "hello_rust_ffi_plugin"
}

// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

5 添加frb依赖

rust/Cargo.toml文件添加依赖, flutter_rust_bridge可换成最新的,现在最新版本是2.0.0-dev.28

toml 复制代码
[dependencies]
flutter_rust_bridge = "=2.0.0-dev.28"

在插件项目中新增文件flutter_rust_bridge.yaml

这个文件是frb生产代码的一些配置,可以参考官网文档

yaml 复制代码
rust_input: rust/src/api/**/*.rs # 需要生成dart的rust代码文件
dart_output: lib/   # rust生成的基础代码目录,我这填的lib

6 生成代码

插件目录下执行

bash 复制代码
flutter_rust_bridge_codegen generate

全部搞定

7 一键创建脚本

为了简化这个流程,我写了一个脚本,只要输入插件名成,自动生成上述所有的配置文件

源码:github.com/mdddj/frb_p...

安装

bash 复制代码
cargo install frb_plugin_tool

运行

bash 复制代码
frb_plugin_tool

8 示例项目

aria2_dart

github: github.com/mdddj/aria2...

pub: pub.dev/packages/ar...

相关推荐
fqbqrr4 小时前
2411rust,实现特征
rust
码农飞飞4 小时前
详解Rust枚举类型(enum)的用法
开发语言·rust·match·枚举·匹配·内存安全
Summer不秃4 小时前
Flutter之使用mqtt进行连接和信息传输的使用案例
前端·flutter
旭日猎鹰4 小时前
Flutter踩坑记录(二)-- GestureDetector+Expanded点击无效果
前端·javascript·flutter
sunly_4 小时前
Flutter:AnimatedSwitcher当子元素改变时,触发动画
flutter
AiFlutter4 小时前
Flutter封装Coap
flutter
一个小坑货9 小时前
Cargo Rust 的包管理器
开发语言·后端·rust
bluebonnet279 小时前
【Rust练习】22.HashMap
开发语言·后端·rust
旭日猎鹰10 小时前
Flutter踩坑记录(三)-- 更改入口执行文件
flutter
旭日猎鹰10 小时前
Flutter踩坑记录(一)debug运行生成的项目,不能手动点击运行
flutter