Reputation: 1932
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?
Upvotes: 5
Views: 3083
Reputation: 1932
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
.
Upvotes: 3
Reputation: 44091
You could put the common parts into a third hierarchy, then include that in your mobile and web hierarchies using local pubspec includes. I'm not sure how you'd publish that to pub if you wanted to share it, although if you're already sharing it, it'd just be three pub repos like you have locally.
Upvotes: 0