Feature flag in flutter using Firebase Remote config

Firebase provide remote config as a cloud service to change the behaviour of app without user updating the app. Feature flags are a way to control the availability of features in your app. By using feature flags, you can roll out new features to a subset of users or to specific segments of your user base. This can be helpful for testing new features, collecting feedback, or A/B testing different versions of a feature.

Let’s get into it.

To use Firebase Remote Config as a feature flag, you first need to create a parameter in the Firebase console. The parameter’s value will be used to control whether or not the feature is enabled. So, first go to your firebase project and select remote config in side nav

Remote config console

Now press Add parameter button here. Now you could create a parameter called enable_feature_x and set its default value to false. This would mean that the new feature would be disabled by default. And Save this configuration.

Add new feature flag

Now publish your changes by pressing Publish changes.

Now all set on console side, let’s go to flutter side :-

First of all we need to add firebase_remote_config as pub dependency. So for that run flutter pub add firebase_remote_config on your console in project directory.

Now, Use below given piece of code to get remote configs

class RemoteConfigProvider {
  final FirebaseRemoteConfig _remoteConfig;

  RemoteConfigProvider(FirebaseRemoteConfig remoteConfig) : _remoteConfig = remoteConfig;

  Future initialise() async {
    try {
      await _remoteConfig.setDefaults(_defaults);
      await _remoteConfig.setConfigSettings(
        RemoteConfigSettings(
          fetchTimeout: const Duration(seconds: 5),
          minimumFetchInterval:
              EnvironmentConfig.PROD ? const Duration(hours: 1) : const Duration(seconds: 0),
        ),
      );
      await _remoteConfig.fetchAndActivate();
      _remoteConfig.onConfigUpdated.listen((configUpdate) {
        _remoteConfig.activate();
      });
    } on Exception catch (e, s) {
      // Track when it fails to fetch
    }
  }

  static const String _enableFeatureX = 'enable_feature_x';
  bool get enableFeatureX => _remoteConfig.getBool(_enableFeatureX);

  final Map<String, dynamic> _defaults = {
    _enableFeatureX : false,
  };
}

Now, lets see how to use it :-

void main() async {
 final remoteConfigProvider = RemoteConfigProvider();
 await remoteConfigProvider.initialise();

  // Check the value of the `enable_feature_x` parameter.
  bool enableFeatureX = remoteConfig.enableFeatureX;

  // If the feature is enabled, show the new feature to the user.
  if (enableFeatureX) {
    // Show the new feature.
    runApp(AppWithFeature());
  } else {
    // Hide the new feature.
    runApp(AppWithoutFeature());
  }
}

Yaay! we did it.

Hope to see you in coming article.