Integrating Rust + Flutter + Kotlin for Mobile Applications
With the introduction of ffi in Dart, things became more smoother now, with a better performance as the interction now is Dart/Rust directly, without a need for Dart/Kotlin/Rust or Dart/Swift/Rust cycle, below a simple example:
First src/lib.rs
#[no_mangle]pub extern fn rust_fn(x: i32) -> i32 { println!("Hello from rust\nI'll return: {}", x.pow(2)); x.pow(2) }
and Cargo.toml
[package]name = "Double_in_Rost"version = "0.1.0"authors = ["Hasan Yousef"]edition = "2018"[lib]name = "rust_lib"crate-type = ["dylib"] # could be `staticlib` as well[dependencies]
Running cargo build --release
will generate target\release\rust_lib.dll
copy/paste it into Dart application root directory
Write Dart code as below:
import 'dart:ffi';import 'dart:io' show Platform;// FFI signature of the hello_world C functiontypedef ffi_func = Int32 Function(Int32 x); //pub extern fn rust_fn(x: i32) -> i32// Dart type definition for calling the C foreign functiontypedef dart_func = int Function(int x);void main() { // Open the dynamic library var path = './rust_lib.so'; if (Platform.isMacOS) path = './rust_lib.dylib'; if (Platform.isWindows) path = 'rust_lib.dll'; final dylib = DynamicLibrary.open(path); // Look up the Rust/C function final my_func = dylib.lookup<NativeFunction<ffi_func>>('rust_fn').asFunction<dart_func>(); print('Double of 3 is ${my_func(3)}');}