11
votes

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
What is a main purpose of getting flavor name? Use different configuration based on flavor name in the dart code? Or you just want to get flavor name? - tatsuDn

4 Answers

17
votes

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;
      }
    });
  }
}
14
votes

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.

3
votes

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.

0
votes

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");