Flutter与Rust|基础配置和开发

1,039 阅读1分钟

项目实践在window环境下进行

安装rust

在rust官网下载rustup-init.exe;运行rustup-init.exe根据提示安装即可。由于本人电脑是windows而且已经安装Visual Studio ,安装选项时使用x86_64-pc-windows-msvc。

Snipaste_2022-06-06_17-27-05.png

使用rust编写lib

创建一个native_rust lib

cargo new --lib native_rust

在lib.rs文件添加一下代码

#[no_mangle]
pub extern "C" fn add(a: i64, b: i64) -> i64 {
    a + b
}

修改Cargo.toml文件,填入一下内容

[package]
name = "native_rust"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[lib]
name ="native_rust"
crate-type = ["cdylib", "staticlib"]

[dependencies]

配置Android NDK环境

在系统属性,环境变量中配置ANDROID_NDK_HOME,设置为本机ndk所在目录。

Snipaste_2022-06-10_21-18-34.png

配置cargo编译条件

将rust代码编译成flutter需要so,需要设置交叉编译目标平台,设置如下

rustup target add aarch64-linux-android armv7-linux-androideabi x86_64-linux-android i686-linux-android

使用cargo-ndk来编译需要so;编译前需要先安装

cargo install cargo-ndk

安装完成后,使用下面的命令编译so

cargo ndk -t armeabi-v7a -t arm64-v8a -t x86_64 -o ./jniLibs build --release

Snipaste_2022-06-10_21-01-07.png

创建flutter工程

flutter create hello_ffi_rust

将jniLibs生成文件放在flutter工程Android目录的相应位置,如下图

Snipaste_2022-06-10_22-15-16.png

在lib目录下,新增ffi_rust.dart,内容如下

import 'dart:ffi';

import 'dart:io';

final DynamicLibrary ccl = Platform.isAndroid
    ? DynamicLibrary.open('libnative_rust.so')
    : DynamicLibrary.process();

final int Function(int x, int y) add = ccl
    .lookup<NativeFunction<Int32 Function(Int32, Int32)>>('add')
    .asFunction();

修改main.dart,将_counter++修改为_counter = add(_counter,2);

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      // _counter++;
       _counter = add(_counter,2);
    });
  }

运行flutter run,运行程序,最终运行效果

ezgif-5-32eda274f4.gif

项目地址flutter_rust