Flutter elegantly distinguishes development and production environments

Flutter elegantly distinguishes development and production environments

update record

  • <2020-12-26 Sat> Android Build


At least two different environments are often encountered in APP development: a test environment and a production environment.

So how can we switch to a different environment without breaking the existing code after we test and develop it?

Fluter official documents did not give a recommended program, looking at different ways that more main_ Enviroment .dart is the most elegant way.

Create different environments

the way

Create a different project in the lib directory main_ Enviroment .dart file, to distinguish between different environments, each containing a different initial configuration main_.dart

Directory Structure

lib/main_com.dart  #  main_com 
lib/main_dev.dart  #  
lib/main_release.dart  #  

Define configuration

Define the configuration class, generally it may be the key, api_url here I just use the most commonly used base_url

enum BuildFlavor { dev, release }

class BuildEnvironment {
  final BuildFlavor flavor;
  final String apiBaseUrl;

  }) : this.flavor = BuildFlavor.dev;

  }) : this.flavor = BuildFlavor.release;

Initial configuration

Initialize different environment configurations, use the configuration as a global variable, or use getIt or getx for dependency injection. I prefer to use dependency injection so that the code can be tested and clear. getx is used in the demo

  1. Test environment main_dev.dart

    void main() async {
      final buildEnv = BuildEnvironment.dev(
        apiBaseUrl: 'https://domain.dev/api',
  2. Production environment main_release.dart

    void main() async {
        final buildEnv = BuildEnvironment.release(
        apiBaseUrl: 'https://domain.release/api',
  3. Total code main_com.dart

    void mainCom() {


  1. Command line configuration flutter run main_dev.dart

  2. Android stuio configuration specified in the configuration file to run main_ Enviroment .dart example test environmentlib/main_dev.dart

  3. Vistual studio configuration.vscode/launch.json

      "version": "0.2.0",
      "configurations": [
          "program": "lib/main_dev.dart",
          "request": "launch",
          "type": "dart"
          "name": "production",
          "program": "lib/main_prod.dart",
          "request": "launch",
          "type": "dart"


Specify the desired environment packaging flutter build -t lib/main_/enviroment/.dart

Android Build configuration specified environment

Due to Android build gradle default is looking main.dart then you will find that you might build fail. At this time, you may need to know where to configure. After going through the source code, you only need to add the following to the gradle.properties file

# android/gradle.properties


Like, follow, Star


  1. how-do-i-build-different-versions-of-my-flutter-app-for-qa-dev-prod