Flutter conditionnal import mobile vs desktop
Asked Answered
T

1

6

Importing on web vs native is easy

import '../wrappers/platform/platform_none.dart'
    if (dart.library.io) '../wrappers/platform/platform_io.dart'
    if (dart.library.js) '../wrappers/platform/platform_web.dart';

What if I want to import a different package depending on whether I am on mobile (iOS/Android) vs on desktop (Linux/MacOS/Windows)?

If there is no way with conditional import, how can you achieve that any other way?

Telemetry answered 28/3, 2021 at 9:57 Comment(6)
What specific packages are you using that you would want to exclude between Mobile and Desktop?Alexei
move_to_background, to put an app in the background. Of course this does not make sense with desktop so it's no supported.Telemetry
But is it causing you issues, or are you simply preoccupied with App size?Alexei
Issue, I am developing a cross platform plug-in so sacrificing 3 platform because of conditional import is such a bummer.. I did find a workaround but it basically meant duplicating all the source files of the plug-in I was using, but of course this is not a real solution.Telemetry
The native code of a plugin is only compiled for the specific platform it applies to. Only the Dart code would be included everywhere, and the plugin you mentioned above has only a single 16-line Dart file, including whitespace and comments. The difference between excluding it or not is negligible.Thema
The size is not the issue. This issue is that, if I include this plug-in in mine, mine will loose the desktops badges on pub.dev since move_to_background only supports mobile.Telemetry
T
4

There is no way to do what you are describing; conditional imports only support library-based conditions, and there is no difference in supported libraries for mobile and desktop.

Thema answered 16/4, 2021 at 22:30 Comment(4)
Theorically the dart team could create dummy libraries that would serve this purpose then.Telemetry
Anyway sorry for not accepting earlier after much research you are right it cannot be done with the shipped libraries. I still think it's a pain but anyway ;)Telemetry
@Telemetry have you found a workaround to this?Defeat
@ValentinVignal As I said in one of the comment, one solution for me (having only an Android version of the plugin) was to create a dummy version of the class I needed manually (which only returns error) and then use conditional import. That's not the best but at least it work if you really need to, no matter how tediousTelemetry

© 2022 - 2024 — McMap. All rights reserved.