flutter_rust_bridge icon indicating copy to clipboard operation
flutter_rust_bridge copied to clipboard

[Question] Calling dart code from sync rust

Open gabrielDevlog opened this issue 9 months ago • 2 comments

First of all, thank you for your work — flutter_rust_bridge is fantastic! I have a question about how to call a Dart function from Rust code. I suspect there's something I'm not understanding correctly about async behavior in Rust.

I have an async Rust function that downloads a file and reports its progress via a synchronous callback:

pub async fn download<F>(callback: F) where F: FnMut(u32, u32);

In my Flutter Rust app, I'm trying to call it like this:

pub async fn download(
    dart_callback: impl Fn(u32, u32) -> DartFnFuture<()>,
) {
    let progress_callback = |current: u32, total: u32| {
        dart_callback(current, total).await; // <- this is where I'm stuck
    };

    myRustPackage
        .download(progress_callback)
        .await?;
}

This is pseudo-code, but it shows the core idea. The download itself works, but dart_callback is never called. How can I call this async Dart function from within synchronous Rust code? Or is there a better/different way to handle this when using flutter_rust_bridge?

Thanks in advance!

gabrielDevlog avatar May 22 '25 07:05 gabrielDevlog

You are welcome!

For progress_callback, it seems it accepts a sync function instead of async function. So dart_callback(current, total).await; will not trigger the real operation (which is async).

You may need to search "how to make async function become sync" etc.

fzyzcjy avatar May 22 '25 07:05 fzyzcjy

You could use flutter_rust_bridge::spawn to run the async function within the sync closure. Just keep in mind that things might get messed up when it's called rapidly (like calls going out of order).

anlumo avatar May 28 '25 14:05 anlumo

Close since there seems to be an answer, but feel free to reopen if there are any questions!

fzyzcjy avatar Jul 01 '25 14:07 fzyzcjy

Btw it is impossible to call Dart from sync Rust and require sync Dart output, b/c suppose Rust is on a thread other than main thread, then Dart is on the main thread - a different thread, busy doing some other task

fzyzcjy avatar Jul 01 '25 14:07 fzyzcjy

This thread has been automatically locked since there has not been any recent activity after it was closed. If you are still experiencing a similar issue, please open a new issue.

github-actions[bot] avatar Jul 15 '25 15:07 github-actions[bot]