r/FlutterDev • u/lets4r • Jun 17 '20
Article Flutter and Desktop Apps
https://medium.com/flutter/flutter-and-desktop-3a0dd0f8353e12
u/coldoil Jun 17 '20
I can attest to how well the FFI works. I have a fairly "fat" client to develop, i.e. lots of computation done locally, and performance is a consideration, so the architecture is flutter on the front-end interfacing via FFI with a Rust backend. It works great. Communication between the two languages is done via protocol buffers - I even have a little gRPC implementation working, so it's trivial to send requests to the native code and get responses back. Flutter build packages everything up automatically without any special configuration. I really recommend it if you need to do some computation on the client. (I know not every project needs to do that!)
2
Jun 17 '20
I have the same architecture and I ended up writing my own RPC system that runs over stdin/out, which is great because then you avoid all the issues with listening on local TCP ports, plus it is way simpler than gRPC (do you really want to start a full HTTP2 server just to do IPC?).
Plus I found that gRPC is really inconsistent in its support of streaming, e.g. the gRPC-web stuff doesn't support it, except there is an unofficial implementation that does, but only server streaming, etc.
One big caveat I've found with FFI is there's no way to send events from the non-Dart code to the Dart process. Seems very limiting to me. I don't really see how you can do IO type things without that (other than polling, which sucks).
5
u/coldoil Jun 17 '20 edited Jun 17 '20
I don't run an HTTP2 server for IPC between dart and native - you're right, that would be total overkill (plus I can't imagine the performance would be great). I simply provided my own gRPC implementation for FFI (a stub implementation is already provided in the grpc package, all that's required is an implementation of the transport layer, which in this case took about 50 lines of code).
You can provide a Dart function as a callback to the native side via FFI, which allows you to get events delivered to your Dart code on demand. (Indeed, this is essential in order to get streaming gRPC working across FFI.) I think it was added relatively recently to dart:ffi, though - perhaps you're on an older version of the package which doesn't provide it?
The biggest issue, I think, is deciding on how to ensure both sides of the FFI bridge are guaranteed to be "speaking the same language", which is why I settled on protobufs and gRPC. I'm not usually a fan of generated code but in this case having a makefile spit out protobuf definitions for both dart and rust is a handy way of guaranteeing at compile time that both sides are going to be on the same page. It also makes unit testing via mocked protobufs a realistic possibility.
3
u/HomeDope Jun 17 '20
Do you happen to have any code examples of how gRPC works between Flutter and Rust? Especially the ffi side of things.
7
u/coldoil Jun 17 '20
Sure. I'll try to package up a minimal example repo in the next day or two. Reply to this message if I don't come back in that timeframe to remind me.
1
u/fear_is_the_weakness Jun 18 '20
RemindME! 2 days "Reminder to package up a minimal example repo"
1
u/RemindMeBot Jun 18 '20 edited Jun 19 '20
I will be messaging you in 2 days on 2020-06-20 04:41:56 UTC to remind you of this link
3 OTHERS CLICKED THIS LINK to send a PM to also be reminded and to reduce spam.
Parent commenter can delete this message to hide from others.
Info Custom Your Reminders Feedback 0
3
Jun 17 '20
perhaps you're on an older version of the package which doesn't provide it?
Ah cool, yeah I last looked at this about a year ago so nice that they have added FFI callbacks.
I'm not usually a fan of generated code but in this case having a makefile spit out protobuf definitions for both dart and rust is a handy way of guaranteeing at compile time that both sides are going to be on the same page
Yeah I am doing the same thing. Actually another reason I wrote my own RPC system is that gRPC has some annoying features that aren't at all needed in our situation:
You have to tediously number each field.
Everything is optional.
I just use a standard packed struct encoding (via serde_bincode) so you don't have to number fields, and properly support
Option. (NNBD will make that nicer.)2
u/coldoil Jun 17 '20
Yes, I agree with you that the whole "everything is optional" is a bit annoying. I'm not bothered by the field numbering, I can see the rationale for it and using a standard protocol means switching to a web-based transport is trivial down the line if necessary.
1
u/TheFr0sk Jun 18 '20 edited Jun 18 '20
Isn't Dart on desktop complied to native? I know for mobile it is compiled once the build is done, but for desktop I'm not sure...If that's the case, Dart wasn't performant enough for the computational task you had? I confess I never used Rust, so I don't know how good or bad it might be for heavy computational tasks.Edit: I should have read the article first
2
u/coldoil Jun 18 '20 edited Jun 18 '20
This is an excellent question: how fast is Dart? I compiled a set of cross-language benchmarks to try to establish an answer to this during the first phase of my project. In summary, what I discovered was:
C++ and Rust have comparable performance (not a big surprise)
Java isn't much slower than C++ once the JVM has warmed up - I was surprised by how competitive it was with Rust and C++, I wasn't expecting this (it was only about 15-20% slower in my benchmarks)
The Dart VM is pretty darn fast - about half the speed of C++ and Rust, which is pretty great for a non-compiled language
but (and this is a big "but") when compiled to native (as is the case for desktop and I think for Flutter as well [at least on iOS?]) there is clearly a different approach that doesn't involve the Dart VM because performance is about three times slower than the same code running on the VM (i.e. about six times slower than C++ and Rust).
I was surprised by this. In short, Dart running in the Dart VM, e.g. as a command-line app, is pretty competitive. But Dart compiled to AOT/native is pretty disappointing compared to C++, Rust, Java, and Haxe (another language I included in my benchmarks). So it became clear to me that my two options were (a) just write everything in Java or (b) write the computation-heavy parts of the code in C++ or Rust. Since cross-platform deployment is a goal, writing everything in Java isn't really an option. So Dart/Rust it is!
1
u/malkia Jun 18 '20
It's expected though. A VM over time would have much more information gathered allowing it to optimize hot-paths. AOT is a must when there is no option to provide JIT, and VM has probably initial slower (overall) boot time.
1
u/coldoil Jun 18 '20
I was expecting it to be slower. I wasn't expecting it to run at a third of the speed.
2
u/mraleph Jun 18 '20
Depends on the benchmark - somewhere JIT and AOT are on par, somewhere JIT is much faster than AOT, somewhere AOT is somewhat faster than JIT.
What kind of benchmark did you write? If it was some number crunching then AOT most likely would be slower - though without looking at benchmark it is impossible to say why.
Most common problems are:
lack of type information (i.e. AOT is unable to figure out which concrete type is flowing through some important variables);
poor inlining decisions (i.e. AOT is very conservative with inlining to keep the code size under control - JIT is much more liberal).
boxing of primitive values (i.e. sometimes AOT compiler makes poor decisions around which values should be boxed - most commonly due to the first two issues)
JIT and AOT compiler are using largely the same compilation toolchain - it's just that JIT uses type feedback and speculative optimizations and AOT uses global type flow analysis (TFA) and non-speculative optimizations.
1
u/coldoil Jun 18 '20
Well, here's a simple one: standard n-body problem benchmark, taken from https://salsa.debian.org/benchmarksgame-team/benchmarksgame/
https://gist.github.com/ajrcarey/375b53a52584b36868d2312aaf8e51fc
dart2native ./main.dart; time ./main.exe
real 0m16.192s user 0m15.765s sys 0m0.017s
time dart ./main.dart
real 0m7.190s user 0m6.513s sys 0m0.109s
1
u/mraleph Jun 19 '20
I took a brief look at this, the main issue AOT compiler stumbles upon here is
for (var b in bodies)loop here. If that code is rewritten to use old-school loop like other loops in the same function that removes majority of the difference.for(int nb = 0; nb < bodies.length; nb++) { final b = bodies[nb]; // ... }The reason why original loop causes problem is a bit convoluted - the original code omits types in many places (Dart 1 style), which means among other things that
NBodySystem.bodiesis dynamically typed. Our AOT compiler tries to compensate for lack of type information and actually manages to infer thatbodiesis always going to be aList<Body>- however this information does not survive the trip throughfor (var e in bodies)construct andedoes not get any more precise type inferred than its static type (which isdynamic). I have filed an issue to try and figure out if we could do better.One could ask: well, can I just change
var bodiestoList<Body> bodies, would that solve the issue? It does solve part of the performance problem, but not entirely - another issue withfor(var e in smth)is that we don't do a good job inlining here.Final bit of difference comes from the fact that JIT tracks the length of an array stored in
Body._datafield and uses this information to eliminate bounds checks. There is an issue open for AOT to address this - but we have not done it yet.Actually for AOT you could just rewrite the
Bodyclass code like this:class Body { double x; double y; double z; double vx; double vy; double vz; double mass; Body({this.x, this.y, this.z, this.vx, this.vy, this.vz, this.mass}); }and it would eliminate the indirection through
_dataarray entirely. AOT compiler is capable of fully unboxingdoublefields so it does not need theBody._data = Float64Array(...)trick. The reason why AOT does it and JIT does not - is because it uses non-nullability information inferred by TFA to make field unboxing decisions, JIT only has access to speculative profiling information which is not good enough for this [speculative field unboxing is possible but complicates implementation too much]. Given Dart 2 type system we could non-speculatively unbox all fields of typedoubleand use a value from NaN-space to representnull, but we just decided to wait for NNBD. But anyway, I digress.So with a bit of profiling and couple lines of fixes you can bring performance of this benchmark to JIT numbers.
That said, is this benchmark really representative of the workload your application has to deal with?
→ More replies (0)1
u/malkia Jun 18 '20
Possibly u/mraleph can answer, but there were lots of clues on the issues list for dart - https://github.com/dart-lang/sdk/issues?q=aot+performance
4
u/SoundDr Jun 18 '20
I currently have a Flutter app live on the Mac AppStore 😎 https://apps.apple.com/us/app/widget-studio/id1516549273
2
u/splishyandsplashy Jun 18 '20
Is this more difficult than Electron?
2
u/bartturner Jun 18 '20
Do not think it is more difficult. But what is important is that it is more performant and a lot more secure.
But the two are actually using the same core technology with both using the Skia renderer.
1
u/znjw Jun 18 '20
I'm only missing one point here: where can I find documentation about handling right-click mouse event? I can't find it anywhere on Github.
4
u/eibaan Jun 18 '20
You can use the
Listenerwidget, which emitsPointerEvents which have abuttonsproperty which can be equal tokSecondaryMouseButton.
1
u/unaligned_access Aug 03 '20
I'm interested about the resulting file size on Windows. Any info on that?
1
u/sabaye Jun 18 '20
I changed to masted and enabled windows desktop and them flutter didn't work anymore
1
u/splishyandsplashy Jun 18 '20
what do you means?
1
u/sabaye Jun 18 '20
I switched to the master channel and typed the --enable-windows-desktop and then I couldn't type any flutter command, it will throw a lot errors
1
1
u/BoreHoRahaHaiYaar Jun 18 '20
Did you run flutter upgrade after switching the channel?
1
1
u/malkia Jun 18 '20
What does flutter build -d windows -v does? Sometimes I would delete the "windows" folder, and "flutter create ." it again.
28
u/[deleted] Jun 17 '20
I'm writing a desktop Flutter app and it's going pretty well! There are some bits that are tricky - writing plugins is really hard - and some missing desktop stuff like scrollbars, but overall I like it.