Search code examples
flutterfirebasewebbuildflutter-web

How to setup different firebase environments(Flavors) in Flutter Web


I am trying to set up different firebase environments(for example :qa,prod) in a flutter project.

I created two projects in firebase, one for production, one for the qa. Then, in an iOS or Android project, I using separate google-services.json or GoogleServices-Info.plist files.

but,how to do it in Flutter web?


Solution

  • If you need this dynamic config in dart code, you can create an interface that represents your configs and create implementations for each environment, so you can change the implementation passing a parameter when run flutter app (using --dart-define).

    Imagine the case that you have a prod and an homolog environment, you can create three files:

    The first one is the contract of your configs, that all environments must have implemented.

    abstract class AppConfig {
     String get baseUrl;
    }
    

    And we create a class for each environment, with the implementation of the configs defined in AppConfig.

    class ProdConfig implements AppConfig {
      @override
      String get baseUrl => 'https://my-prod-url.com';
    }
    
    
    class HomologConfig implements AppConfig {
      @override
      String get baseUrl => 'https://my-homolog-url.com';
    }
    

    When we need to get the config class, we instantiate based on parameter passed by --dart-define

    AppConfig getConfig() {
      const environmentParameter = String.fromEnvironment('ENV');
      switch (environmentParameter) {
        case 'prod': return ProdConfig();
        case 'homolog': return HomologConfig();
        default: throw Error(); // You can set a default environment
      }
    }
    

    And when you run your app, you just need to pass this parameter, like the example below:

    flutter run --dart-define ENV=prod
    

    Or in homolog:

    flutter run --dart-define ENV=homolog
    

    BUT, if you need to set configs like firebase, you should check this answer