how to get flavor name on Flutter?

Viewed 9136

Is it possible to get flavor name Flutter side? for both android and ios

build.gradle

flavorDimensions "app"

productFlavors {
    dev {
        dimension "app"
        versionCode 2
        versionName "1.0.0"
    }
    qa {
        dimension "app"
        applicationId "com.demo.qa"
        versionCode 3
        versionName "1.0.2"
    }
}
4 Answers

As long as every flavor has a different packageName you could do it like this:

enum EnvironmentType { dev, qa }

class Environment {
  EnvironmentType current;

  Environment() {
    PackageInfo.fromPlatform().then((PackageInfo packageInfo) {
      switch (packageInfo.packageName) {
        case "com.demo.qa":
          current = EnvironmentType.qa;
          break;
        default:
          current = EnvironmentType.dev;
      }
    });
  }
}

You could use the solution from jonahwilliams.

  1. Set a key-value pair when creating the app:
flutter build apk --flavor=paid --dart-define=app.flavor=paid
  1. Access the value in Dart:
const String flavor = String.fromEnvironment('app.flavor');

void main() {
  print(flavor);
}

This would print "paid" when run.

The advantages are that you can use this on platforms where flavors are not supported yet and that the variable is const. The disadvantage that you have to set the key-value pair for the build.

There is not a simple way to know the flavor name, however I would suggest you to use an environment variable, loaded from flutter_dotenv for example.

file .env

FLAVOR=dev

file main.dart

void main() async {
  await DotEnv().load('.env');
  final flavor = DotEnv().env['FLAVOR'];

  String baseUrl;
  if (flavor == 'dev') {
    baseUrl = 'https://dev.domain.com';
  } else if (flavor == 'qa') {
    baseUrl = 'https://qa.domain.com';
  } else {
    throw UnimplementedError('Invalid FLAVOR detected');
  }
}

This will allow you (as developer) to easily change the behaviour of your app and switch from different environments seamlessy.

Just write a channel method for that.

 override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)

        channel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL)
        channel.setMethodCallHandler { call, result ->
            when (call.method) {
                "getFlavor" -> {
                    result.success(BuildConfig.FLAVOR)
                }
            }
        }
    }

Than in dart:

final flavor = platform.invokeMethod("getFlavor");
Related