Search code examples
flutterflutter-dependencies

How to exclude unnecessary dependency packages when only releasing for certain platform?


I am creating a dart http library for flutter apps. I learned from here that each different platform needs different http client implementation, like cronet_http, cupertino_http, fetch_client. So i have to include all the possible dependencies in the package's pubspec.yaml, and using conditional import.

The question is, if i only want to release my app on one certain platform, be it android. Will dependencies for iOS and web be included in his app? if so, the app size would gonna be unnecessarily larger than required.

Edit:

It's hard to check whether the unnecessary dependencies included or not, because for cronet_http or cupertino_http, i think it's only about several bytes in size. So instead, i am trying to derive the conclusion that, if cupertino_http is not used in the finally released Android app, but it's included, it will be certainly increase the size of the app by some extent. Do i have to really make an app for this library and check whether it's several bytes larger than expected, so that i am qualified to ask my question?

I imagined that there would be one approach like below to exclude the unnecessary dependencies:

  1. specify cronet_http and cupertino_http as optional dependencies, like there is android_dependencies, or ios_dependencies, besides dependencies in pubspec.yaml.
  2. And let the library users select which dependency to include in his/her release, with the dependencies.

Or keep the optional dependencies in dev_dependencies and optionally detect and import the one included, then let users select which one in their dependencies.

Good to know there is a treeshaking algo in flutter to remove those unnecessary dependency codes. But i can hardly find some docs about it from google, only a few blogs discussing about it, just more confuse, like what this issue says.

Edit2: https://www.reddit.com/r/FlutterDev/comments/101k1f9/does_flutter_only_compile_code_related_to_the/

Last but not least, to allow for tree shaking, your conditional code that picks one implementation instead of another must be evaluable at compile time. So a if (someComplexCondition) DesktopWidget() else MobileWidget() might not be sufficient. Notice that kIsWeb is a compile time constant.

As for the Dart code, well, most of it is intended to run on all platforms, but if there's some code that only runs on one platform, putting that code inside a if(Platform.isSomePlatform) will make Dart tree shaking remove the code if it's running on another platform.


Solution

  • Normally Darts linker is pretty good to remove all that isn't needed using its treeshaking algorithm. Especially plugins will always only include the platform-specific code that is used for that platform in your final app. In general, unless you find a problem with size or performance don't try to optimize without need.