# Remote config in Flutter, step by step

Source: https://appfig.com/guides/remote-config-in-flutter

Add appfig_flutter to pubspec.yaml, await AppFig.init before runApp, then read values with getFeatureValue and a fallback. No app update needed after that.

To add remote config to a Flutter app, install a config package, initialize it before `runApp`, and replace each hard-coded value you want to control with a lookup that falls back to today's value. With AppFig that is one entry in `pubspec.yaml`, one `await AppFig.init(...)`, and `await AppFig.getFeatureValue('key')` where the value is used; after one release, changes are published from the dashboard and reach users without an app update.

AppFig's Flutter package is a thin layer over the native AppFig SDKs for Android and iOS, so rules behave exactly as they do in a native app: they are downloaded once, evaluated on the device, and can target by what the user has done. (Firebase Remote Config also has a Flutter plugin, [`firebase_remote_config`](https://firebase.google.com/docs/remote-config/flutter/get-started); this guide covers the AppFig setup.)

## Step 1: Install the package

Minimum versions: Android 5.0 (API 21) and iOS 12.

Add this to `pubspec.yaml` and run `flutter pub get`:

```yaml
dependencies:
  appfig_flutter:
    git:
      url: https://github.com/smartconfigui/AppFig-SDKs.git
      path: flutter
      ref: v2.5.0
```

The package is installed from Git; it is not on pub.dev. Nothing has to be added to the Android or iOS projects: the plugin pulls in the Android SDK and the iOS framework ships inside it. The `ref` pins the version.

## Step 2: Initialize before runApp

Use the company id, app id and API key from the AppFig dashboard:

```dart
import 'package:appfig_flutter/appfig_flutter.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await AppFig.init(companyId: 'your-company', tenantId: 'your-app', env: 'prod', apiKey: 'your-api-key');
  runApp(const MyApp());
}
```

`init` completes when rules are available or after `readyTimeout` (5 seconds by default), so values read right after it are real, and a slow network cannot hold the first frame for longer than the timeout.

## Step 3: Read a value with a fallback

Values are stored as strings. `getFeatureValue` returns `null` when no rule matches, so parse it and fall back:

```dart
// Read a value (null when no rule matches)
final maxSongs = int.tryParse(await AppFig.getFeatureValue('max_songs') ?? '') ?? 25;
```

The `?? 25` at the end is the important part. Make it the number the app uses today, and the app behaves exactly as before until you publish a rule. It also covers a first launch with no connection, when there are no rules on the device yet.

A switch is the same thing with the values `"on"` and `"off"`; the package also has `isFeatureEnabled` for that case.

Now create `max_songs` in the dashboard, add a rule with no conditions and the value `50`, and publish. Once the new rules reach the device, the lookup returns `50`.

## Step 4: Re-read when rules change

The SDK checks for changes every minute by default while the app is in the foreground. To apply a new value without waiting for a restart, listen for updates:

```dart
// Re-read values when new rules arrive
AppFig.onRulesUpdated.listen((_) => refreshLimits());
```

Decide per value whether that is what you want. A limit can change live; a layout the user is looking at is usually better left until the next screen load.

## Step 5: Log events and set user properties

A single value for every user is only the start. Tell AppFig what the user does and who they are, and rules can target on both:

```dart
// Tell AppFig what the user does and who they are; rules can target on both
AppFig.logEvent('add_song', parameters: {'source': 'import'});
AppFig.setUserProperty('subscription_tier', 'free');
```

Log an event when the action happens. Set a property when the value is known and again when it changes, for example after a purchase. The package also has `logScreenView`, `removeUserProperty`, `setDeviceProperty` and `setAppVersion`.

## Step 6: A rule based on user behavior

Suppose free users who have added at least 20 songs in the last week should get a higher limit, because they are engaged and close to hitting the wall. The rule on `max_songs`:

```json
{
  "max_songs": [
    {
      "conditions": {
        "events": {
          "mode": "simple",
          "operator": "AND",
          "items": [
            {
              "key": "add_song",
              "count": { "operator": ">=", "value": 20 },
              "within_last_days": 7
            }
          ]
        },
        "user_properties": [
          {
            "key": "subscription_tier",
            "value": { "operator": "==", "value": "free" }
          }
        ],
        "user_properties_operator": "AND",
        "device": [],
        "device_operator": "AND"
      },
      "value": "100"
    }
  ]
}
```

You build this in the dashboard's rule builder; the JSON is what the device downloads. A few things to know:

- Event, user property and device conditions must all pass for the rule to match.
- Rules on a feature are checked top to bottom and the first match wins, so put this rule above the general one ([rule prioritization](/docs/rule-prioritization)).
- Device conditions can use properties such as `platform`, `os_version`, `language` and `country`.
- Events can also be matched by parameter (`param`) or as a sequence of steps. The [rule schema](/docs/rule-schema) lists every option.

Because the rule is evaluated on the device against events the app just logged, the user gets the higher limit when the twentieth song is added. There is no audience to sync and no network call per check.

## Step 7: Test it

Start with the smallest possible rule. Create a feature `test_feature` with one rule that requires the event `test_event` at least once and returns `"success"`, publish, then:

```dart
// Before the event: no rule matches
print(await AppFig.getFeatureValue('test_feature')); // null

AppFig.logEvent('test_event');

// After the event
print(await AppFig.getFeatureValue('test_feature')); // success
```

If the second read is still `null`, check the feature name (it is case-sensitive), confirm the rule was published and not only saved as a draft, and check the ids and API key passed to `init`. The package also has `hasRulesLoaded` and `refreshRules` for checking and reloading rules. More checks are in the [testing guide](/docs/testing).

Then check the two failure paths yourself: put the device in airplane mode on a fresh install and confirm the fallback is used, and remove the rule and confirm the app returns to today's behavior.

## Step 8: Run an A/B test on the value

Once a value is read from AppFig, testing it needs no new code. A/B tests work without a user id: a device without one is assigned by its device id, and the assignment stays with the device across restarts and sign-in. Call `setUserId` before `init` if a signed-in user should get the same variant on every device.

To see experiments in your analytics tool, connect it once at startup:

```dart
AppFig.connectAnalytics(
  setUserProperty: (name, value) =>
      FirebaseAnalytics.instance.setUserProperty(name: name, value: value.isEmpty ? null : value),
  logEvent: (name, parameters) =>
      FirebaseAnalytics.instance.logEvent(name: name, parameters: parameters),
);
```

`setUserProperty` receives one property per running experiment (`af_<experiment>` = variant). `logEvent` receives `appfig_experiment` when the device enters an experiment and `appfig_feature` when the app reads a feature. The two callbacks can call any analytics tool. How winners are decided is in [Experiments](/docs/experiments).

## Skip the manual steps

If the project is on GitHub, the [guided setup](/docs/guided-setup) can do the install for you: it scans the Flutter code for values that could change without a release and opens one pull request that installs the SDK, adds event logging for the events rules will target, and reads the values you pick, each with today's value as the default. Nothing is written to the repository until you open that pull request.

For the full package reference, see [Flutter integration](/docs/flutter-integration). For a use of all this on a real screen, see [How to change your paywall without an app update](/guides/change-paywall-without-app-update).

## FAQ

### Is the AppFig Flutter package on pub.dev?

No. It is installed from Git with the `git:` entry shown above, pinned to a tag with `ref`. Nothing else needs adding to the Android or iOS projects.

### What does getFeatureValue return when there is no connection?

Rules are stored on the device and evaluated there, so with rules already downloaded you get the same answer offline. On a first launch with no connection there are no rules yet, the call returns `null`, and your fallback is used.

### Do I need Firebase to use AppFig in Flutter?

No. The package works on its own. Connecting an analytics tool through `connectAnalytics` is what lets you see experiments in your reports, and the two callbacks can call any tool.

### How quickly does a published change reach the app?

The SDK checks for changes every minute by default while the app is in the foreground. Listen to `onRulesUpdated` to re-read values as soon as new rules arrive.

### How much does remote config for Flutter cost with AppFig?

The Lite plan is free for one app with 5 configs and one A/B test at a time. The Full plan is $99 per app a month, never per user, fetch or seat; see [pricing](/#pricing).
