GithubHelp home page GithubHelp logo

fzyzcjy / flutter_rust_bridge Goto Github PK

View Code? Open in Web Editor NEW
3.6K 20.0 254.0 186.37 MB

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

Home Page: https://fzyzcjy.github.io/flutter_rust_bridge/

License: MIT License

Rust 35.91% Dart 58.77% C 4.37% Shell 0.04% Kotlin 0.01% Swift 0.01% Objective-C 0.01% HTML 0.02% Ruby 0.07% CMake 0.22% C++ 0.22% JavaScript 0.28% Just 0.01% Dockerfile 0.01% PowerShell 0.01% Batchfile 0.02% MDX 0.02% TypeScript 0.04% CSS 0.01%
dart flutter rust bindgen ffi

flutter_rust_bridge's Introduction

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

Click to expand
  • 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.
  • New codec: A new codec, SSE, which is several times faster under typical workload.

Please visit this page for more information and update guide.

I want to keep it in beta for a while (though CI has all passed), to allow publishing API breaking changes, and hear your thoughts and suggestions about it!

🍀 What's this?

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

📚 Quickstart

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

cargo install 'flutter_rust_bridge_codegen@^2.0.0-dev.0' && \
    flutter_rust_bridge_codegen create my_app && cd my_app && flutter run

(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.

2. Simplicity

  • 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

  • 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).
  • 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

  • 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?

Click 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

Simple Rust...

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

...called from Dart, without manual intervention.

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

Example 2: Show off skills ;)

Let's see how fancy we can support:

// ↱ Arbitrarily fancy Rust types
struct Garden { land: whatever::fancy::Land }

// ↱ Complex but auto-translatable
enum Tree { A { name: (String, i32), children: Option<Vec<Tree>> }, B }

// ↱ Support functions & methods
impl Garden {
    // ↱ Allow async & sync Rust
    async fn plant(
        // ↱ Support T/&T/&mut T
        &mut self,
        tree: Tree,
        // ↱ Rust can also call Dart
        chooser: impl Fn(String) -> bool,
        // ↱ Error translation ; zero copy
    ) -> Result<Vec<u8>, FancyError> {
        ...
    }
}

Still seamlessly call in Dart:

var tree = Tree.a(('x', 42), [Tree.b()]);
// ↱ Async & sync Dart
print(await garden.plant(tree, (a) => true));

💡 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):

fzyzcjy
fzyzcjy

💻 📖 💡 🤔 🚧
Viet Dinh
Viet Dinh

💻 ⚠️ 📖
rogurotus
rogurotus

💻 📖
Nicolas Gasull
Nicolas Gasull

💻
Joshua Wade
Joshua Wade

💻
Lattice 0
Lattice 0

💻 📖
Unoqwy
Unoqwy

💻
Anton Lazarev
Anton Lazarev

💻
sagu
sagu

💻 📖
Sebastian Urban
Sebastian Urban

💻
Rom's
Rom's

💻 📖
老董
老董

💻 📖
Gregory Conrad
Gregory Conrad

📖 💻
huang12zheng
huang12zheng

💻 📖
Daniel
Daniel

💻
Manuel Philipp
Manuel Philipp

💻 📖
SoLongAnd...
SoLongAnd...

💻 📖
hsfzxjy
hsfzxjy

💻
Cupnfish
Cupnfish

💻
alanlzhang
alanlzhang

💻 📖
Erikas Taroza
Erikas Taroza

💻
菘菘
菘菘

💻
SimplyKyle!
SimplyKyle!

💻
Zaitam
Zaitam

💻
Brent Lewis
Brent Lewis

💻 📖
nitn3lav
nitn3lav

💻 📖
Kevin Li
Kevin Li

💻 📖
Alex Procelewski
Alex Procelewski

📖 💻
Daniel Porteous (dport)
Daniel Porteous (dport)

📖
Andreas Monitzer
Andreas Monitzer

💻
Kim Dong-Hyun
Kim Dong-Hyun

💻 📖
NightFeather
NightFeather

💻
九月
九月

💻
Wouter Ensink
Wouter Ensink

📖
Marcel
Marcel

💻
Aidan
Aidan

📖
Debanjan Basu
Debanjan Basu

📖
Patrick Auernig
Patrick Auernig

💻
Sai Chaitanya
Sai Chaitanya

💻
Xidorn Quan
Xidorn Quan

💻
jsonmona
jsonmona

💻
mtz
mtz

💻
codercengiz
codercengiz

💻
Michael Bryan
Michael Bryan

💻
Patrick Mukherjee
Patrick Mukherjee

💻
Aran Donohue
Aran Donohue

💻
Philip Kannegaard Hayes
Philip Kannegaard Hayes

💻
SilverMira
SilverMira

💻
Sander in 't Hout
Sander in 't Hout

💻
Haled Odat
Haled Odat

💻
王宇逸
王宇逸

💻
bus710
bus710

📖
._.
._.

📖
Marc Gutenberger
Marc Gutenberger

💻
Andrii Stadnik
Andrii Stadnik

💻
syndim
syndim

💻
Rhian Moraes
Rhian Moraes

📖
Ares Andrew
Ares Andrew

📖
polypixeldev
polypixeldev

📖
CicadaCinema
CicadaCinema

💻 📖
CosmicHorror
CosmicHorror

💻
Akash Gurava
Akash Gurava

💻
Fabian Löschner
Fabian Löschner

💻
Vincent Herlemont
Vincent Herlemont

💻
wxitcode
wxitcode

📖
canxin
canxin

💻
pixelshot91
pixelshot91

📖
TrackerSB
TrackerSB

💻
Dampfwalze
Dampfwalze

📖
Samuel Cavalcanti
Samuel Cavalcanti

📖
Roman Zaynetdinov
Roman Zaynetdinov

📖
raphaelrobert
raphaelrobert

📖
Mouayad Alhamwi
Mouayad Alhamwi

📖
elliotsayes
elliotsayes

📖
muji
muji

📖
thomas725
thomas725

📖
orange soeur
orange soeur

📖
Alex Gorichev
Alex Gorichev

📖
Sven-Hendrik Haase
Sven-Hendrik Haase

📖
Chris Ohk
Chris Ohk

📖
Vitalii Hurianov
Vitalii Hurianov

📖
Sam Nystrom
Sam Nystrom

📖
mattiasgronlund
mattiasgronlund

💻
Antonio D'souza
Antonio D'souza

📖
max
max

📖
Jonathan
Jonathan

📖
Akash Jaiswal
Akash Jaiswal

📖
Febrian Setianto
Febrian Setianto

📖
Satvik Pendem
Satvik Pendem

💻
Damien Wise
Damien Wise

📖
rustui
rustui

📖
J
J

📖
Ikko Ashimine
Ikko Ashimine

📖
thesimplekid
thesimplekid

📖

More specifically, thanks for all these contributions:

  • Desdaemon: Support not only simple enums but also enums with fields which gets translated to native enum or sealed freezed class in Dart. Support the Option type as nullable types in Dart. Support Vec of Strings type. Support tuple type. Support comments in code. Add marker attributes for future usage. Add Linux and Windows support for with-flutter example, and make CI works for that. Avoid parameter collision. Overhaul the documentation and add several chapters to demonstrate configuring a Flutter+Rust project in all five platforms. Refactor command module. Precompiled binary CI workflow. Fix bugs. Add support for the Web platform, parallel to the existing mobile/desktop platforms, via WASM and JavaScript as intermediate values. GitHub retry actions. Implement draft of opaque types. Refactor Boxed and Option. Impl list of dates and optionals. Parameter defaults. Refactor CLI. Refactor codegen errors. Refactor for performance.
  • rogurotus: Add Rust opaque types, enabling arbitrary Rust structs to be used as opaque Dart objects by generating wrappers and raw Arc pointers. Also add Dart opaque types, allowing to use any Dart objects in Rust code. Extend SyncReturn for more types. Fix generation bug. Fix SyncReturn. Migrate to dart-sys. Update CI. Fix linters. Fix SyncReturn bug.
  • ngasull: Make sync mode support whatever types that classical async mode supports. Bump sdk.
  • SecondFlight: Allow structs and enums to be imported from other files within the crate by creating source graph. Auto-create relevant dir. Fix store_dart_post_cobject error with ffigen 6.0.
  • lattice0: Implement hierarchy of exceptions. Support methods, such that Rust struct impls can be converted to Dart class methods. StreamSink at any argument.
  • Unoqwy: Add struct mirrors, such that types in the external crates can be imported and used without redefining and copying.
  • antonok-edm: Avoid converting syn types to strings before parsing to improve code and be more robust.
  • sagudev: Make code generator a lib. Add error types. Depend on cbindgen. Fix LLVM paths. Update deps. Fix CI errors.
  • surban: Support unit return type. Skip unresolvable modules. Ignore prefer_const_constructors. Non-final Dart fields.
  • Roms1383: Fix build_runner calling bug. Remove global ffigen dependency. Improve version check. Fix enum name-variant conflicts. Support Chrono date time and UUID types. Migrate to Rust 1.64 workspace. Update and refactor CI. Update header comments. Code cleanup.
  • dbsxdbsx: Allow generating multiple Rust and Dart files. Fix lint. Update doc. Add logging.
  • GregoryConrad: Add doc to setup frb inside a Dart/Flutter library.
  • huang12zheng: Support type aliases and nested ones. Tweak code generation. Fix rust_build_and_test on Mac. Improve CI logic and cache. Remove bridge field in model.
  • trobanga: Add support for [T;N] structs. Add usize support. Add a cmd argument. Separate dart tests. Fix fallible list case. Fix test compile. Fix Result + RustAutoOpaque.
  • MnlPhlp: Support macros and will auto expand. Allow mirror types in streams.
  • SoLongAndThanksForAllThePizza: Refactor and enhance SyncReturn to support more types. Refactor post-release CI.
  • hsfzxjy: Fix SyncReturn use-after-free bug.
  • Cupnfish: Support arrays as function parameters. Allow multi mirror.
  • alanlzhang: Add generation for Dart metadata. Enhance and fix module parser. Fix enum in struct. Fix linter. Improve hints.
  • erikas-taroza: Support list of primitive enums. Make enum camelCase. Warn wrong path. Fix cargo expand.
  • SiongSng: Finish implementing exception hierarchy. Fix SyncReturn bug.
  • JustSimplyKyle: Also finish implementing exception hierarchy. Allow ignore function.
  • Zaitam: Fix when method return struct. Partial migration to Dart 3.
  • coder0xff: Discuss binding unmodified Rust. Refactor SupportedInnerType. Extra codegen tester.
  • nitn3lav: Nested structs without Box.
  • AlienKevin: Add flutter example for macOS. Add doc for Android NDK bug. Improve migration doc.
  • alexthe2: Add Option Datetime. Add empty structs. Improve doc. Add r#. Fix mirror enum bug.
  • banool: Fix pubspec parsing. Fix symbol-stripping doc.
  • anlumo: Fix freezed + methods. Non-clone RustOpaque.
  • temeddix: Fix broken CI. Custom num workers. Fix MacOS doc steps. Update doc. Make zero-copy defaultable.
  • NightFeather0615: Fix Vec bool.
  • OfficialBoyfriend: Fix error display.
  • w-ensink: Improve doc. Fix CI. Refactor. Add tests.
  • smw-wagnerma: Improve Windows encoding handling.
  • powpingdone: Document JNI init and libc++_static linking.
  • debanjanbasu: Document alternative NDK init.
  • valeth: Rename callFfi's port.
  • sccheruku: Prevent double-generating utility.
  • upsuper: Refactor delegate-attr.
  • jsonmona: Add import.
  • MateusHBR: Add pub get.
  • codercengiz: Fix mirroring bug.
  • Michael-F-Bryan: Detect broken bindings.
  • patmuk: Set MSRV. Fail fast. Improve message. Improve docs.
  • aran: Fix map + mirror. Fix pubspec. Upgrde ffigen. Bump version. Fix typo.
  • phlip9: Fix no-serde compilation.
  • SilverMira: Fix StreamSink.
  • h3x4d3c1m4l: Fix when outside folder.
  • HalidOdat: Improve config method. Hint build.rs.
  • Berrysoft: Fix missing symbols.
  • bus710: Add a case in troubleshooting.
  • Demezy: Mention troubleshooting.
  • gutenfries: Bump proc-macros.
  • anstadnik: Check keywords.
  • syndim: Add a bracket to box.
  • rhian-cs: Add Cargo workspace doc.
  • TENX-S: Improve doc. Reproduce a bug.
  • polypixeldev: Improve doc.
  • CicadaCinema: Bump version. Improve doc.
  • CosmicHorrorDev: Change deps.
  • akashgurava: Partial fix.
  • w1th0utnam3: Improve message.
  • vincent-herlemont: Loosen version.
  • wxitcode: Add org option. Fix a typo.
  • canxin121: Fix permission.
  • pixelshot91: Update cargokit. Fix doc link.
  • TrackerSB: Bump allo-isolate.
  • Dampfwalze: Improve doc.
  • samuel-cavalcanti: Improve doc.
  • zaynetro: Improve doc.
  • raphaelrobert: Remove oudated doc.
  • DMouayad: Improve doc.
  • elliotsayes: Improve doc.
  • tmpfs: Improve doc.
  • thomas725: Improve doc.
  • juzi5201314: Improve doc.
  • Voklen: Improve doc.
  • svenstaro: Improve doc.
  • utilForever: Fix typos.
  • not-holar: Fix typos.
  • Stonks3141: Fix doc credit.
  • mattiasgronlund: Bump version.
  • adsouza: Fix doc grammar.
  • vimaxwell: Fix doc link.
  • lker-dev: Fix doc link.
  • jaiakash: Fix doc link.
  • feber: Fix doc link.
  • satvikpendem: Little co-work #989.
  • damywise: Fix a typo.
  • rustui: Fix a typo.
  • escwxyz: Fix a typo.
  • eltociear: Fix a typo.
  • thesimplekid: Fix a typo.

flutter_rust_bridge's People

Contributors

alanlzhang avatar alexthe2 avatar allcontributors[bot] avatar anlumo avatar coder0xff avatar cupnfish avatar dbsxdbsx avatar dependabot[bot] avatar desdaemon avatar erikas-taroza avatar fzyzcjy avatar gregoryconrad avatar gutenfries avatar huang12zheng avatar justsimplykyle avatar lattice0 avatar mergeable[bot] avatar mnlphlp avatar ngasull avatar nightfeather0615 avatar rogurotus avatar roms1383 avatar sagudev avatar samuel-cavalcanti avatar secondflight avatar siongsng avatar solongandthanksforallthepizza avatar temeddix avatar trobanga avatar w-ensink avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

flutter_rust_bridge's Issues

Use CI to check *published* packages can be used correctly, especially when following README; then, add this workflow.yml to readme as another reference; even try to run in windows if possible

a bit related: "Test your install and setup steps." https://github.com/ddbeck/readme-checklist/blob/main/checklist.md#help-the-reader-use-the-project

for example, to test in master, we do cargo run -- xxx. but an end user will do cargo install flutter_rust_bridge_codegen, then execute that binary.

different environments may lead to different results. so this may be helpful.

however, how to do this, especially if the example itself is incompatible with the old published version?
well, should be compatible most of the times...

platform:

  • linux
  • macos
  • windows

code base:

  • pure_dart?

Follow Flutter's official guide of writing a good README

https://dart.dev/guides/libraries/writing-package-pages

  • Put a short description at the top
  • Include visual content
  • Use lists to present important information
  • Include usage examples
  • Use Dart code formatting
  • Mention related terms
  • Tell users where to go next

it also gives some links. (Learn more about good README authoring) pasted below

Proposal (vote to enable it): call function once, return multiple times (the `Stream`)

This is currently a proposal. If you want it, please vote for this issue.

Flutter's Stream is a powerful abstraction. When using it as the return value of Rust function, we can allow the scenario that we call function once, and then return multiple times.

For example, your Rust function may run computationally heavy algorithms, and for every hundreds of milliseconds, it finds out a new piece of the full solution. In this case, it can immediately give that piece to Flutter, then Flutter can render it to UI immediately. Therefore, users do not need to wait for the full algorithm to finish before he can see some partial results on the user interface.

Detail steps

  • add tests
  • parser
  • generator rust
  • generator dart
  • rust runtime
  • dart runtime
  • pass compile
  • stream's close
  • pass tests

Publish to Rust Crate and Flutter Pub

Originally #4, but since that thread is used for discussing names, I create a new issue.

  • automate by CI
  • change README and slogan #24
  • change tag #25
  • don't forget it is 1.0.1, not 1.0.0 (before)
  • publish rust codegen crate (will need to change name)
  • publish rust crate
  • publish flutter crate
  • auto run when a "release" is created

Missing license.

Describe the bug
This code is not have a license and is therefore closed source.

Expected behavior
A LICENSE file in the repository.

Additional context
Posting the repository publicly does not make it open source.

Anything you write is automatically copyrighted unless you explicitly license it. The vast majority of Rust projects use the MIT license, but you can do whatever you feel is best. I think the website I linked above can walk you through choosing a license and adding a LICENSE file to your codebase.

codegen produces dart code with incorrect types, including on examples - caused by external tool `ffigen` fail to find `stdarg.h` headers

Hey, I'm trying to try this out, and I'm having an issue even get basic examples to work. The generated store_dart_post_cobject method has an incorrect type, resulting in an error:

lib/bridge_generated.dart:52:9: Error: The parameter 'ptr' of the method 'RustWire.store_dart_post_cobject' has type 'int', which does not match the corresponding type, 'Pointer<NativeFunction<Uint8 Function(Int64, Pointer<Void>)>>', in the overridden method, 'FlutterRustBridgeWireBase.store_dart_post_cobject'.
 - 'Pointer' is from 'dart:ffi'.
 - 'NativeFunction' is from 'dart:ffi'.
 - 'Uint8' is from 'dart:ffi'.
 - 'Int64' is from 'dart:ffi'.
 - 'Void' is from 'dart:ffi'.
Change to a supertype of 'Pointer<NativeFunction<Uint8 Function(Int64, Pointer<Void>)>>', or, for a covariant parameter, a subtype.
    int ptr,
        ^
../../../../.pub-cache/hosted/pub.dartlang.org/flutter_rust_bridge-1.0.3/lib/src/basic.dart:77:8: Context: This is the overridden method ('store_dart_post_cobject').
  void store_dart_post_cobject(

This happens even when trying to regenerate the example code! Is it possible the code generator is out of sync with the library code? (I installed it for these tests directly from the most recent master, but first ran into the issue with the version on crates.io)

Specifically for the example - running flutter_rust_bridge_codegen --rust-input rust/src/api.rs --dart-output dart/lib/bridge_generated.dart in frb_example/pure_dart/dart results in the non-whitespace changes (generated with: git diff -w --word-diff-regex='[^[:space:]]' lib/bridge_generated.dart) far below, and attempting to run the code results in the error immediately below:

+ dart compile exe lib/main.dart -o main.exe
Info: Compiling with sound null safety
lib/bridge_generated.dart:616:9: Error: The parameter 'ptr' of the method 'FlutterRustBridgeExampleWire.store_dart_post_cobject' has type 'int', which does not match the corresponding type, 'Pointer<NativeFunction<Uint8 Function(Int64, Pointer<Void>)>>', in the overridden method, 'FlutterRustBridgeWireBase.store_dart_post_cobject'.
 - 'Pointer' is from 'dart:ffi'.
 - 'NativeFunction' is from 'dart:ffi'.
 - 'Uint8' is from 'dart:ffi'.
 - 'Int64' is from 'dart:ffi'.
 - 'Void' is from 'dart:ffi'.
Change to a supertype of 'Pointer<NativeFunction<Uint8 Function(Int64, Pointer<Void>)>>', or, for a covariant parameter, a subtype.
    int ptr,
        ^
../../../frb_dart/lib/src/basic.dart:77:8: Context: This is the overridden method ('store_dart_post_cobject').
  void store_dart_post_cobject(
       ^
lib/bridge_generated.dart:98:15: Error: The argument type 'NativeFunction<Int32 Function(Pointer<Int32>)>' can't be assigned to the parameter type 'Pointer<NativeFunction<Int32 Function(Pointer<Int32>)>>'.
 - 'NativeFunction' is from 'dart:ffi'.
 - 'Int32' is from 'dart:ffi'.
 - 'Pointer' is from 'dart:ffi'.
              _api2wire_bool(myBool)),
              ^
lib/main.dart: Warning: Interpreting this as package URI, 'package:flutter_rust_bridge_example/main.dart'.
lib/main.dart:25:110: Error: The argument type 'bool' can't be assigned to the parameter type 'NativeFunction<Int32 Function(Pointer<Int32>)>'.
 - 'NativeFunction' is from 'dart:ffi'.
 - 'Int32' is from 'dart:ffi'.
 - 'Pointer' is from 'dart:ffi'.
        await api.primitiveTypes(myI32: 123, myI64: 10000000000000, myF64: 12345678901234567890.123, myBool: true), 42);
                                                                                                             ^
Error: AOT compilation failed
Generating AOT kernel dill failed!
  void wire_primitive_types(
    int port,
    int my_i32,
    int my_i64,
    double my_f64,
    {+ffi.Pointer<+}bool{+>+} my_bool,
  ) {
    return _wire_primitive_types(
      port,
  void wire_primitive_types(
    int port,
    int my_i32,
    int my_i64,
    double my_f64,
    {+ffi.Pointer<+}bool{+>+} my_bool,
  ) {
    return _wire_primitive_types(
      port,
      my_i32,
      my_i64,
      my_f64,
      my_bool[-? 1 : 0-],
    );
  }

  late final _wire_primitive_typesPtr = _lookup<
      ffi.NativeFunction<
          ffi.Void Function(ffi.Int64, ffi.Int32, ffi.Int64, ffi.Double,
              ffi.[-U-]{+Po+}int[-8-]{+er<bool>+})>>('wire_primitive_types');
  late final _wire_primitive_types = _wire_primitive_typesPtr
      .asFunction<void Function(int, int, int, double, {+ffi.Po+}int{+er<bool>+})>();
  void store_dart_post_cobject(
    [-DartPostCObjectF-]{+i+}n[-Type-]{+t+} ptr,
  ) {
  late final _store_dart_post_cobjectPtr =
      _lookup<ffi.NativeFunction<ffi.Void Function([-DartPostCObjectF-]{+ffi.I+}n[-Type-]{+t32+})>>(
          'store_dart_post_cobject');
  late final _store_dart_post_cobject =
      _store_dart_post_cobjectPtr.asFunction<void Function([-DartPostCObjectF-]{+i+}n[-Type-]{+t+})>();
}
typedef[-DartPostCO-] b[-jectFnType = ffi.P-]o[-inter<-]{+ol =+} ffi.NativeFunction<ffi.[-Ui-]{+I+}nt[-8-]{+32+} Function([-DartPort,-]ffi.Pointer<ffi.[-Void>)>>;-]
[-typedef DartPort = ffi.-]Int[-64-]{+32>)>+};

Add Flutter quick start example and related documentation

  • think about an example
  • make it runnable
  • documentation
  • beautify the flutter gui
  • beautify the generated mandelbrot
  • well the mandelbrot is still ugly. change it
  • beautify the returned text...
  • move unrelated to to utils.dart
  • edit CI such as code formatting to consider this new sub-package
  • add CI to run it in Android
  • add CI to run it in iOS (not the same as android)

Flaky tests

Flutter tests sometimes just time out. That is highly unlikely to be caused by our code, since at that stage, the flutter code seems not to be started yet.

The first line of our testing code is print('integration_test/main.dart starts!');. But that is even not printed.

e.g. a successful test

image

a failed test even does not have that

https://github.com/fzyzcjy/flutter_rust_bridge/runs/3823673349

with different attempts, sometimes phone A fails, sometimes phone B fails

e.g. https://github.com/fzyzcjy/flutter_rust_bridge/actions/runs/1314605741/attempts/2

Choose a good name for this library

Context

In addition to what is discussed in this issue, there are also some discussions in Reddit:

https://www.reddit.com/r/rust/comments/q0wrhr/comment/hfbnom7/?utm_source=share&utm_medium=web2x&context=3

Names for other code generators

Let's look at how others name it.

python

  • pyo3 4.7k
  • rust-cpython 1.5k
  • milksnake 0.7k (inactive)

c/c++

  • cxx 3.2k
  • cbindgen 1.2k
  • autocxx 1.2k
  • cc-rs 0.8k
  • rust-cpp 0.5k
  • flapigen-rs 0.5k (multi language)

java

  • flapigen-rs 0.5k (multi language)
  • jni-rs 0.5k
  • java-rust-example 0.3k
  • j4rs 0.2k
  • robusta 0.1k
  • rjni 0.06k

javascript/js/node

  • neon 5.8k
  • napi-rs 1.1k
  • node-bindgen 0.2k

go/golang

  • rust-plus-golang 0.3k
  • rure-go 0.2k

Official doc

https://rust-lang.github.io/api-guidelines/naming.html

Crate names should not use -rs or -rust as a suffix or prefix. Every crate is Rust! It serves no purpose to remind users of this constantly.

rust-lang/api-guidelines#29

Most downloaded crates

https://crates.io/crates?sort=recent-downloads

  • cfg-if
  • range_core
  • rand
  • syn
  • proc-macro2
  • libc
  • unicode-xid
  • quote
  • getrandom
  • rand_chacha
  • autocfg
  • serde
  • bitflags
  • memchr
  • base64
  • lazy_static

Simplfy generated files: Merge generated_api.dart and generated_wire.dart, making it easier to use; Also, do not have postfix like the "wire" in generated_wire.rs - those are impl details instead of what users should know

  • Merge generated_api.dart and generated_wire.dart, making it easier to use
  • do not have postfix like the "wire" in generated_wire.rs
  • Simplify the constructor - currently ExampleApi constructor relies on ExampleWire... (change constructors)
  • make the finally used class an abstract class
  • make wire class, api class all file-private
  • extract "import" to above
  • move generated data structs to above
  • write function declarations to the abstract api class

Incorrectly handle the Uint8List

generated dart code:

ffi.Pointer<wire_uint_8_list> _api2wire_uint_8_list(Uint8List raw) {
  return _api2wire_uint_8_list(raw.0);
}

[Feature Request] Desktop support?

It's very inspiring to have such a library for those who like both flutter and rust, but it would be better if it can also support the desktop. Any plans on that ?

Refactor and polish code to make it neater

  • extract the "Executor" logic, such that people can implement their own
  • add comments for code
  • refactor main.rs, originally too messy
  • explain the config file
  • add logging, originally all are println, which will make readers confused by tons of messy outputs

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.