Project Icon

flutter_rust_bridge

Flutter和Rust跨语言绑定生成工具

flutter_rust_bridge是一个Flutter/Dart和Rust的绑定生成工具。它支持任意类型转换、异步调用、双向函数调用,可处理整个文件夹输入,兼容现有库工具。作为Flutter Favorite项目,它简单易用yet功能强大,为Flutter和Rust开发提供了高效的连接方案。

flutter_rust_bridge v2: Flutter/Dart <-> Rust binding generator, feature-rich, but seamless and simple.

Rust Package Flutter Package Stars CI Post-Release codecov All Contributors Codacy Badge

Logo

What's new in V2

Tap to expand
  • From 1.x to 2.0.0-dev.0:
    • Rapid setup: Only a one-liner command to integrate into your project.
    • Arbitrary types: Use arbitrary Rust and Dart types without manual intervention, even if they are not serializable or non-clone (previously need some manual intervention).
    • Async Rust: Support asynchronous Rust (async fn), in addition to sync Rust / async Dart / sync Dart.
    • Rust call Dart: Allow Rust to call Dart functions (previously only allow Dart to call Rust).
    • Support whole folders as inputs: Previously only support one single file (e.g. api.rs).
    • Use libraries/tools in Flutter/Rust: All existing libraries, Flutter debuggers, ... Nothing to stop you from using them.
  • From 2.0.0-dev.0 to 2.0.0:
    • Parsing third-party packages: Scan and use existing Rust packages in Dart (experimental).
    • Lifetimes: Support returning types with lifetime specifiers (experimental).
    • Traits: Support traits as base classes and trait objects.
    • New codec: A new codec, SSE, which is several times faster under some workloads.
    • Others (>200 PRs): Auto and manual accessors, object proxies, user-defined serializers, developer experience, deadlock-free auto locking, Rust initializers, included batteries, renaming and ignoring, improving streams, more types, ...

Please visit this page for more information and update guide.

🍀 What's this?

  • Just write down normal Rust code (even with arbitrary types, closure, &mut, async, traits, etc)
  • And call it from Flutter, as if Rust code is normal Flutter code
  • The bridge will generate all glues in between

📚 Quickstart

Create a working Flutter + Rust app and see it live, by running:

cargo install flutter_rust_bridge_codegen && flutter_rust_bridge_codegen create my_app && cd my_app && flutter run
Expand optional steps

(Optional) Edit rust/src/api/simple.rs (e.g. Hello -> Hi), then see the change by:

flutter_rust_bridge_codegen generate && flutter run

For more elaborated quickstart, please visit this page.

🚀 Advantages

1. Officially Flutter Favorite

This package is officially Flutter Favorite, and is in the first batch of 7 packages at its rebooting. (another link)

2. Simplicity

(Tap to expand) Rapid setup, Write your code naturally, Use libraries/tools in Flutter/Rust, Battery included
  • Rapid setup: Only a one-liner command to integrate into your project.
  • Write your code naturally: Use your intuition and write the code you want. The bridge understands many advanced grammars (see below), allowing seamless calling Rust from Dart.
  • Use libraries/tools in Flutter/Rust: All existing libraries, Flutter debuggers, ... Nothing to stop you from using them.
  • Battery included: Even small things like logging and enable backtraces are configured in the starter kit.

3. Powerfulness

(Tap to expand) Arbitrary types, Async & sync, Two-way road, Auto-translatable types, Parsing third-party packages, Auto safety, Customizable & bare-metal mode, Cross-platform, ...
  • Arbitrary types: Use arbitrary Rust and Dart types without manual intervention, even if they are not serializable or non-clone.
  • Async & sync x Rust & Dart: Multi modes for various needs - Async Dart to avoid blocking the main thread, sync Dart for places needed (e.g. Widget.build); async Rust for IO bound tasks, thread pools for CPU-heavy computations.
  • Two-way road: Not only can Dart call Rust - Rust can also call Dart.
  • Auto-translatable types: Lots of types can be further translated to Dart native types, e.g. complex enums and structs, zero-copy big arrays, errors (Result), and Streams (iterator).
  • Parsing third-party packages: Scan and use existing Rust packages in Dart (experimental).
  • Auto safety: Focus on your code, and forget memory safety, malloc/free, or undefined behavior completely.
  • Customizable & bare-metal mode: Provide sensible defaults, but everything (loader, handler, ...) can be customized. You can even throw all away and only use the bare minimum calling.
  • Cross-platform: Support Android, iOS, Windows, Linux, MacOS, and Web.
  • Other features, e.g. support whole folders as input, pure-Dart compatible, instance and static methods, ...

4. Reliability

(Tap to expand) Solid CI, Used by many people, Easy to review, Fast, Hackable, Ask questions
  • Solid CI: Valgrind & sanitizers (ASAN/MSAN/LSAN) for memory/UB-related bugs, testing per platform per mode, benchmarking, test coverage, post-release, etc, all guaranteed by CI.
  • Used by many people: See here for an incomplete list.
  • Easy to code-review & convince yourself: This package simply simulates how humans write boilerplate code. If you want to convince yourself (or your team) that it is safe, there is not much code to track.
  • Fast: It is only a thin (though feature-rich) wrapper, benchmarked on CI, and even has multiple codecs for best performance under different workloads.
  • Hackable: If (for whatever reason) you want to hack the source, there are contributor guides, code is modular, and the execution logic is intuitive.
  • Ask questions: Feel free to ask questions in the issue tracker, and I usually reply within hours (if not sleeping).

Why Flutter + Rust?

Tap to expand

Firstly, super briefly introduce each component (you can find much more in a lot of blogs and posts):

  • Flutter: Cross-platform, hot-reload, rapid-development, flexible UI toolkit.
    • "The most popular cross-platform mobile SDK" (by StackOverflow [1][2]).
  • Rust: Highly efficient and performant, reliable, productive.
    • "The most desired programming language" for 8 years (by StackOverflow and GitHub [1][2]).

Typical scenarios to combine them include:

  • UI framework for Rust: When you want a UI framework for your Rust system.
  • Use arbitrary Rust libraries in Flutter: When the desired functionality only has a library in Rust, not Dart (Flutter).
  • Need high-performance code for Flutter: Rust makes it easy and performant to write multi-thread code, algorithms, data-intensive operations, SIMD code, etc.
  • ...

✨ Show me the code

Example 1

Simple Rust...

fn f(a: String, b: Vec<MyEnum>) -> MyStruct { ... }

...called from Dart, without manual intervention.

print(f(a: 'Hello', b: [MyEnum.c('Tom')]));

Example 2

Suppose we implement a word dictionary in Rust:

// ↱ Arbitrarily fancy Rust types
pub struct WordDict { .. }

// ↱ Support functions & methods
impl WordDict {
    //          ↱ Can call Dart back                 ↱ Translate errors
    pub fn open(chooser: impl Fn(String) -> bool) -> Result<WordDict> { .. }

    // ↱ Support async & sync Dart; property getter
    #[frb(sync, getter)]
    //          ↱ Support T/&T/&mut T
    pub fn size(&self) -> u32 { .. }

    //  ↱ Allow async & sync                    ↱ Support stream (iterator)
    pub async fn search(&self, keyword: String, sink: StreamSink<String>) { .. }
}

Still seamlessly call in Dart:

final dict = await WordDict.open((situation) => true);
print(dict.size);
await for (final value in dict.search('something')) { print(value); }

There are still many features not covered here, such as parsing third party packages, lifetimes, traits, auto accessors, proxies, etc.

💡 Documentation

Check out the documentation for quickstart, full guides and more.

📎 P.S. Achieve ~60 FPS, no matter how janky the Flutter app was due to build/layout

Here is my another open-source library :) https://github.com/fzyzcjy/flutter_smooth.

✨ Acknowledgments and contributors

Firstly, I want to sincerely thank Dart, Flutter and Rust (alphabetical order). Dart provides a solid foundation for productive UI development, Flutter enables developers to make cross-platform apps with ease, and Rust empowers everyone to build reliable and efficient software. Without the languages and frameworks, this bridge connects absolutely nothing. Besides, I also want to express my thanks for conferring the official Flutter Favorite honor to the package. In addition, I also want to say thanks to the Dart, Flutter and Rust team members as well as community members, who have helped me during the development of flutter_rust_bridge by valuable discussions, insights, and actions.

Secondly, thanks goes to these wonderful contributors (emoji key following all-contributors specification):

项目侧边栏1项目侧边栏2
推荐项目
Project Cover

豆包MarsCode

豆包 MarsCode 是一款革命性的编程助手,通过AI技术提供代码补全、单测生成、代码解释和智能问答等功能,支持100+编程语言,与主流编辑器无缝集成,显著提升开发效率和代码质量。

Project Cover

AI写歌

Suno AI是一个革命性的AI音乐创作平台,能在短短30秒内帮助用户创作出一首完整的歌曲。无论是寻找创作灵感还是需要快速制作音乐,Suno AI都是音乐爱好者和专业人士的理想选择。

Project Cover

有言AI

有言平台提供一站式AIGC视频创作解决方案,通过智能技术简化视频制作流程。无论是企业宣传还是个人分享,有言都能帮助用户快速、轻松地制作出专业级别的视频内容。

Project Cover

Kimi

Kimi AI助手提供多语言对话支持,能够阅读和理解用户上传的文件内容,解析网页信息,并结合搜索结果为用户提供详尽的答案。无论是日常咨询还是专业问题,Kimi都能以友好、专业的方式提供帮助。

Project Cover

阿里绘蛙

绘蛙是阿里巴巴集团推出的革命性AI电商营销平台。利用尖端人工智能技术,为商家提供一键生成商品图和营销文案的服务,显著提升内容创作效率和营销效果。适用于淘宝、天猫等电商平台,让商品第一时间被种草。

Project Cover

吐司

探索Tensor.Art平台的独特AI模型,免费访问各种图像生成与AI训练工具,从Stable Diffusion等基础模型开始,轻松实现创新图像生成。体验前沿的AI技术,推动个人和企业的创新发展。

Project Cover

SubCat字幕猫

SubCat字幕猫APP是一款创新的视频播放器,它将改变您观看视频的方式!SubCat结合了先进的人工智能技术,为您提供即时视频字幕翻译,无论是本地视频还是网络流媒体,让您轻松享受各种语言的内容。

Project Cover

美间AI

美间AI创意设计平台,利用前沿AI技术,为设计师和营销人员提供一站式设计解决方案。从智能海报到3D效果图,再到文案生成,美间让创意设计更简单、更高效。

Project Cover

AIWritePaper论文写作

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

投诉举报邮箱: service@vectorlightyear.com
@2024 懂AI·鲁ICP备2024100362号-6·鲁公网安备37021002001498号