1

I have the following app structure:

- Main app (Android native)
 - Flutter module (aar)
  - Flutter plugin

The main Android App uses a Flutter module that contains some Flutter plugins. One of this plugins requires a set of dart-define variables.

I could add the --dart-define argument on Flutter module AAR build, but there's some internal factors that makes this option not so good.

So, my question is, there's a way to add this dart-define settings inside the Flutter plugin (in the gradle scripts)?

Thanks!

siega
  • 2,508
  • 1
  • 19
  • 22
  • I think I found what you are looking for, once refer to this link https://itnext.io/flutter-1-17-no-more-flavors-no-more-ios-schemas-command-argument-that-solves-everything-8b145ed4285d. – Shubhanshu Kashiva Apr 22 '23 at 06:20

1 Answers1

1

Yes, you can add Dart define variables to your Flutter plugin through Gradle scripts.

In build.gradle file of your Flutter plugin module Add the below code to the android section of the file:

    android {
    defaultConfig {
        ...
        buildConfigField "String", "MY_DART_DEFINE_VAR", 
    "\"my_dart_define_value\""
        ...
     }
    }

In your Flutter plugin Dart code, you can access the value of the build config field,

import 'package:flutter/services.dart' show rootBundle;

    const String myDartDefineVar = String.fromEnvironment('MY_DART_DEFINE_VAR', 
    defaultValue: 'default_value');

    // Example usage
    Future<String> getAssetContent(String assetPath) async {
      return await rootBundle.loadString(assetPath);
    }

The String.fromEnvironment method will retrieve the value of the MY_DART_DEFINE_VAR build config field and assign it to the myDartDefineVar constant. If the build config field is not defined, it will use the default value default_value.

You can use the myDartDefineVar constant in your Flutter plugin code as needed.

Remember that you will need to rebuild your Flutter plugin module and update the AAR file in your main Android app to use the updated plugin with the new Dart define variables.

Esmaeil Ahmadipour
  • 840
  • 1
  • 11
  • 32
sachinM
  • 46
  • 2