[Question] Calling dart code from sync rust
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!
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.
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).
Close since there seems to be an answer, but feel free to reopen if there are any questions!
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
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.