Search code examples
flutterdartflutter-web

Do apps built with Flutter suffer from dead code?


Flutter may technically allow you to code once and build an app for multiple platforms, but realistically you do not want to have the same experience on mobile as you do on web or desktop. Its easy to think of solutions to this - "use this widget if on iOS else use this one", or "use mobile view if on mobile else desktop".

Will flutter also take care of treeshaking the machine code so that bundle for the web app isnt 5 times larger than it needs to be?


Solution

  • The treeshaker only removes code that is known to not be in use at compile time. You need to be aware of that when writing the code as it is not magic.

    You can use conditional branching on constants to achieve this.

    const isPlatform = true;
    
    class SomeWidget extends StatelessWidget {
      @override
      Widget build(context) {
        if (isPlatform) {
          return PlatformWidget(); // will appear in build
        } else {
          return SomeOtherWidget(); // will be removed from build
        }
      }
    }
    

    For the web we have kIsWeb but for other platforms there are sadly no compile time constants.

    You can however use dart-define to pass constants to a build.

    const isAndroid = bool.fromEnvironment('IS_ANDROID'); // defaults to false if not supplied
    
    class SomeWidget extends StatelessWidget {
      @override
      Widget build(context) {
        if (isAndroid) {
          return AndroidWidget(); // will appear in build
        } else {
          return SomeOtherWidget(); // will be removed from build
        }
      }
    }
    

    flutter build apk --dart-define=IS_ANDROID=true

    Treeshaking is only performed on release builds.