Search code examples
flutterflutter-dependenciesflutter-webpubspec

Flutter is it possible to import specific libraries based on device type in pubspec.yaml


Two of my apps have the exact same issue at the moment. They are both web and mobile apps with flutter and need to use conflicting packages in pubspec.yaml depending on the web or mobile app.

The first is this:

google_maps_flutter: ^2.0.6
google_maps_flutter_web: ^0.3.0+2

google_maps_flutter doesn't support web, so I need a seperate web plugin google_maps_flutter_web. However if the the web plugin is in the pubspec file when building iOS it will not build because it doesn't have the correct pods.

The second is this:

cloud_firestore: ^2.3.0
firebase_database: ^7.1.1
firebase: ^9.0.1

This is a similar issue cloud_firestore and firebase_database I need to access Firestore and Realtime on apps. Firebase for accessing both on web. Again the problem is if you leave the Firebase in the pubspec.yaml the build fails because it doesn't have the correct pods.

I know I can just split them into two apps which will fix the problem. But I am wondering if there is a way of only installing the correct plugins for the correct platform. I was thinking something like build flavors or some type of dependency injection but my searches have turned up nothing. Have you seen anything like this done before?

Thanks


Solution

  • You may want to use a conditonal import like so:

    import 'package:google_maps_flutter/google_maps_flutter.dart' if(dart.library.js) 'package:google_maps_flutter_web/google_maps_flutter_web.dart';
    

    You can learn more about it in this article.