Search code examples
flutterdarttree-shaking

Tree-shaking vs selective import in Flutter?


In Dart, we have the ability to selectively import parts of files or libraries with the show keyword...


    import 'package:http/http.dart' show get;

...but Flutter makes tree-shaking. Has the show keyword any benefit in Flutter or is it completely meanless?


Solution

  • import/exports directives have nothing to do with tree-shaking.

    show/hide/as are instead used to not pollute the auto-complete, keep some classes "private", or resolve conflicts.

    Say you're using both RxDart and Mobx: both packages define an Observable class.

    If you tried to import both package:rxdart/rxdart.dart; and package:mobx/mobx.dart in the same file, then you would have a conflict.

    You would, therefore, need to use show/hide/as to tell the compiler what's the solution.

    It could be:

    • "I don't care about Mobx's Observable":
    import 'package:rxdart/rxdart.dart';
    import 'package:mobx/mobx.dart' hide Observable;
    
    • "I want only Mobx's "reaction":
    import 'package:rxdart/rxdart.dart';
    import 'package:mobx/mobx.dart' show reaction;
    
    • "I'll use an alias because I may use both"
    import 'package:rxdart/rxdart.dart' as rxdart;
    import 'package:mobx/mobx.dart' as mobx;