fzyzcjy / flutter_rust_bridge

Flutter/Dart <-> Rust binding generator, feature-rich, but seamless and simple.
https://fzyzcjy.github.io/flutter_rust_bridge/
MIT License
4.25k stars 297 forks source link

How to conditionally compile modules? #2221

Closed yzkj2213 closed 1 month ago

yzkj2213 commented 2 months ago

I have two functions, one for windows and one for android。

/api/mod.rs

... other
#[cfg(target_arch = "x86_64-pc-windows-msvc")]
pub mod ssh;
#[cfg(target_arch = "armv7-linux-androideabi")]
pub mod serialport;

but flutter_rust_bridge_codegen generate seem not support target arch or os, when I exec flutter run -d Windows, hint me method from serialport is not defined

welcome[bot] commented 2 months ago

Hi! Thanks for opening your first issue here! :smile:

fzyzcjy commented 2 months ago

Yes, iirc this is not yet supported, but feel free to PR! Alternatively, maybe make the mod unconditional. For example, is it possible to do something like

#[cfg(target_arch = "x86_64-pc-windows-msvc")]
#[path = "ssh.rs"]
pub mod ssh;
#[cfg(target_arch = "armv7-linux-androideabi")]
#[path = "serialport.rs"]
pub mod ssh;
fzyzcjy commented 1 month ago

Think about this again, and I guess it would be good to use the alternative approach above, and the code may also be cleaner: The Dart code can call one single function, instead of calling multiple functions according to platform.

More generally, for example, let's say we have something fancy like

#[cfg(all(target_arch = "x86_64-pc-windows-msvc", target_pointer_width = "32")]
pub mod ssh;
#[cfg(any(target_arch = "armv7-linux-androideabi", target_pointer_width = "64")]
pub mod serialport;

Then if frb does support conditional compilation, Dart code will be:

if (Platform.isWindows && magically_know_is_32_bit) {
  ssh.something();
} else if (Platform.isAndroid || !magically_know_is_32_bit) {
  serialport.somthing();
}

Then that may be a bit errorprone, since we need to carefully align the if and the cfg manually.

On the other hand, if we use the alternative suggestion

#[cfg(all(target_arch = "x86_64-pc-windows-msvc", target_pointer_width = "32")]
#[path = "ssh.rs"]
pub mod hello;
#[cfg(any(target_arch = "armv7-linux-androideabi", target_pointer_width = "64")]
#[path = "serialport.rs"]
pub mod hello;

Then our dart code is

hello.something();

And no worry about the manual if.

Feel free to reopen if needed!

github-actions[bot] commented 1 month ago

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.