Skip to content

🎯 Targeting Huawei builds using --dart-define in Flutter

 at 

I was working on a project where I had to build and publish the app for Huawei devices on AppGallery. The Google Maps is not available for Huawei, so, I had to use OpenStreetMap instead of Google Maps when the app was running on Huawei devices.

In Flutter, we have Platform.isAndroid and Platform.isIOS to check whether the app is running on Android or iOS. But there is no direct way to check whether the app is running on a Huawei device or not. Before, I was defining a boolean value on my AppConstants as buildingForHuawei and setting it to true when I’m building the APK for Huawei AppGallery, and to false when I’m building for Google Play. When that value was true I was displaying the OpenStreetMap and the Google Maps when false. This was a error-prone as I remember when I forgot to change it to false and published the app to Google Play with OpenStreetMap.

A better solution to this is the --dart-define flag with. Define a buildingForHuawei variable in the code as follows:

const bool buildingForHuawei = bool.fromEnvironment('BUILDING_FOR_HUAWEI');

This value comes from the --dart-define flag when building the app. When building the app for Huawei AppGallery, run the following command:

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

And when building the app for Google Play, run the following command:

flutter build apk --dart-define=BUILDING_FOR_HUAWEI=false

Or you can emit the --dart-define flag to use the default value of false:

flutter build apk

And in the code use the buildingForHuawei variable to display different maps:

if (buildingForHuawei) {
  // Show OpenStreetMap
} else {
  // Show Google Maps
}

Additionally, for running the app with this flag in VSCode, add the following configurations to launch.json file:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Debug - Standard",
      "request": "launch",
      "type": "dart",
      "program": "lib/main.dart"
    },
    {
      "name": "Debug - Huawei",
      "request": "launch",
      "type": "dart",
      "program": "lib/main.dart",
      "toolArgs": ["--dart-define", "BUILDING_FOR_HUAWEI=true"]
    }
  ]
}

This was one of the helpful use cases of the --dart-define flag in Flutter which can be used for many other purposes.


Further reading:



Subscribe to the newsletter
Kamran Bekirov

I'm Kamran Bekirov
Built over 70 mobile apps.
Building UserOrient for Flutter
Solo apps: LibroKit, Beyt
Packages: logarte, versionarte
Reach: X, LinkedIn, Instagram, GitHub