Flutter platform specific dependencies
This is possible using conditional imports. You can find an example of the syntax here: https://github.com/dart-lang/site-www/issues/1569. However, I can't seem to find the official documentation for this language feature.
import 'stub.dart'
if (dart.library.io) 'io.dart'
if (dart.library.html) 'html.dart';
Define methods in stub.dart
throwing UnsupportedOperationException
or something the like. It doesn't really matter since stub.dart
isn't going to be imported anyway. Put the actual implementations in io.dart
and html.dart
, respectively. The signatures have to match those in stub.dart
.
You probably only want to do this conditional import at a single point in your program so I highly recommend hiding everything behind a common interface defined somewhere else than in stub.dart
(common.dart
in this example). You can then import and implement common.dart
in io.dart
and html.dart
and use conditional import to chose your implementation at your program root. This way everything else only needs to depend on common.dart
.
Marvin
Updated on December 14, 2022Comments
-
Marvin over 1 year
I want to build an app for Android, iOS and web from a single Codebase using Flutter. Since web does not support all Flutter plugins yet, I'll have to use alternatives that have dependencies (for example
dart:html
) which aren't available on Android and iOS.How can I inject the right implementation depending on the platform on which the application runs, without loading unnecessary/unavailable packages?