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?

Lulupointu
  • 3,364
  • 1
  • 12
  • 28
  • What specific packages are you using that you would want to exclude between Mobile and Desktop? – J. S. Mar 28 '21 at 15:21
  • move_to_background, to put an app in the background. Of course this does not make sense with desktop so it's no supported. – Lulupointu Mar 28 '21 at 19:03
  • But is it causing you issues, or are you simply preoccupied with App size? – J. S. Mar 28 '21 at 23:21
  • 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. – Lulupointu Mar 29 '21 at 07:48
  • 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. – smorgan Apr 16 '21 at 22:44
  • 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. – Lulupointu Apr 17 '21 at 08:01

1 Answers1

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.

smorgan
  • 20,228
  • 3
  • 47
  • 55
  • 1
    Theorically the dart team could create dummy libraries that would serve this purpose then. – Lulupointu Apr 17 '21 at 08:00
  • 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 ;) – Lulupointu Sep 23 '21 at 08:57
  • @Lulupointu have you found a workaround to this? – Valentin Vignal Nov 01 '21 at 03:01
  • @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 tedious – Lulupointu Nov 01 '21 at 08:33