Skip to content
Ergon Code

Ergon CMS · Documentation

Flutter apps

Build an iOS and Android app for a website's customers with Flutter — the generated client, sign-in, the session, blocks, checkout with Stripe, push and tickets.

This guide builds an app for one Ergon CMS website: its content, its shop, bookings and tickets, and the customer's account. Everything goes through the Site API; no secret key is shipped in the app.

1. Generate the client

Each site describes itself — with exactly its active plugins — at /api/site/v1/openapi.json. Generate a Dart client from it:

npx @openapitools/openapi-generator-cli generate \
  -i https://your-site.example/api/site/v1/openapi.json \
  -g dart-dio -o packages/site_api \
  --additional-properties=pubName=site_api
cd packages/site_api && dart run build_runner build --delete-conflicting-outputs

Add it to the app's pubspec.yaml as a path dependency (site_api: {path: packages/site_api}). Re-run the generator when the site gets a new plugin. A client generated from a site with every plugin active is available as a zip to look around in.

2. One Dio for everything

final dio = Dio(BaseOptions(baseUrl: 'https://your-site.example/api/site/v1'));

dio.interceptors.add(InterceptorsWrapper(
  onRequest: (options, handler) async {
    options.headers['Accept-Language'] = Intl.getCurrentLocale().split('_').first;
    options.headers['X-App-Version'] = '${Platform.operatingSystem}/${packageInfo.version}';
    final session = await storage.read(key: 'session');      // flutter_secure_storage
    if (session != null) options.headers['X-Session-Token'] = session;
    final access = await storage.read(key: 'access');
    if (access != null) options.headers['Authorization'] = 'Bearer $access';
    handler.next(options);
  },
  onResponse: (response, handler) async {
    final issued = response.headers.value('X-Session-Token');
    if (issued != null) await storage.write(key: 'session', value: issued);
    handler.next(response);
  },
));
dio.interceptors.add(RefreshOn401(dio, storage));   // below
final api = SiteApi(dio: dio);

The session token is what keeps the cart: store it the first time the server hands one out and send it on every call.

Renewing the token

Refresh tokens work once, so two requests must never refresh at the same time. Queue them behind one refresh:

class RefreshOn401 extends QueuedInterceptor {
  RefreshOn401(this.dio, this.storage);
  final Dio dio; final FlutterSecureStorage storage;

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) async {
    final refresh = await storage.read(key: 'refresh');
    if (err.response?.statusCode != 401 || refresh == null || err.requestOptions.path.contains('/auth/')) {
      return handler.next(err);
    }
    try {
      final r = await Dio(BaseOptions(baseUrl: dio.options.baseUrl))
          .post('/auth/refresh', data: {'refresh_token': refresh});
      await storage.write(key: 'access', value: r.data['data']['access_token']);
      await storage.write(key: 'refresh', value: r.data['data']['refresh_token']);
      final retry = err.requestOptions..headers['Authorization'] = 'Bearer ${r.data['data']['access_token']}';
      handler.resolve(await dio.fetch(retry));
    } on DioException {
      await storage.delete(key: 'access'); await storage.delete(key: 'refresh');
      handler.next(err);                     // show the sign-in screen
    }
  }
}

3. Start with /bootstrap

final boot = (await dio.get('/bootstrap')).data['data'];
final min = boot['app']['min_version'][Platform.isIOS ? 'ios' : 'android'] as String;
if (min.isNotEmpty && Version.parse(packageInfo.version) < Version.parse(min)) {
  return ForceUpdateScreen(storeUrl: boot['app']['store_url'][Platform.isIOS ? 'ios' : 'android']);
}
if (boot['app']['maintenance'] == true) return MaintenanceScreen(message: boot['app']['message']);

boot['theme'] has the site's colours for ThemeData, boot['features'] decides which tabs exist (shop, booking, events, membership, chat …), boot['legal'] links privacy, imprint and terms.

4. Pages and blocks

Pages and posts come as blocks. Draw the ones in boot['blocks']['native'] (heading, rich-text, image, quote, divider, columns, audio) with your own widgets; every block also carries html for everything else:

Widget block(Map b) => switch (b['type']) {
  'heading' => Text(b['data']['text'], style: Theme.of(context).textTheme.headlineSmall),
  'image'   => CachedNetworkImage(imageUrl: b['data']['image']['sizes']['large'] ?? b['data']['image']['url']),
  _         => HtmlWidget(b['html'] ?? ''),              // flutter_widget_from_html
};

A members-only page answers 403 with error.code == 'members_only' and a paywall (tier, whether to sign in, join_url).

5. Signing in

// Email and password
final r = await dio.post('/auth/login', data: {'email': email, 'password': password, 'device': deviceName});
// → 422 two_factor_required: ask for the code, send again with 'code'
// → 403 email_not_verified: a code was emailed; POST /auth/email/verify {email, code}

// Apple (sign_in_with_apple) and Google (google_sign_in): send the ID token
final apple = await SignInWithApple.getAppleIDCredential(scopes: [AppleIDAuthorizationScopes.email, AppleIDAuthorizationScopes.fullName]);
await dio.post('/auth/social/apple', data: {'id_token': apple.identityToken, 'name': apple.givenName});

Every way returns access_token and refresh_token; keep both in flutter_secure_storage. Fill the app's ids under Settings → API → Apps for your customers first, or the server refuses the tokens.

Passkeys: POST /auth/passkey/options gives a challenge_id and WebAuthn options for the platform passkey API (for example the passkeys package); send the result to POST /auth/passkey. iOS needs the associated domain webcredentials:your-site.example, Android the signing fingerprint in the settings.

Deleting the account is a store requirement: DELETE /me with the password (or, for Apple/Google accounts, a code from /auth/password/forgot).

6. Cart and checkout

await dio.post('/cart/items', data: {'product_id': product['id'], 'quantity': 1});
final checkout = (await dio.get('/checkout', queryParameters: {'country': 'DE'})).data['data'];
// show checkout['cart']['totals'], checkout['gateways'], the terms link from checkout['legal']

final placed = (await dio.post('/checkout',
  options: Options(headers: {'Idempotency-Key': const Uuid().v4()}),
  data: {'email': email, 'gateway': gateway, 'terms': true, 'billing_address': address},
)).data['data'];

Then by placed['payment']['status']:

switch (placed['payment']['status']) {
  case 'client':                                         // flutter_stripe
    Stripe.publishableKey = placed['payment']['data']['publishable_key'];
    await Stripe.instance.initPaymentSheet(paymentSheetParameters: SetupPaymentSheetParameters(
      paymentIntentClientSecret: placed['payment']['data']['client_secret'], merchantDisplayName: boot['site']['name']));
    await Stripe.instance.presentPaymentSheet();
  case 'redirect':                                       // PayPal, Klarna …
    await launchUrl(Uri.parse(placed['payment']['url']), mode: LaunchMode.inAppBrowserView);
  case 'pending':
    showInstructions(placed['payment']['instructions']);
}
// then poll GET /orders/{reference}?access=… until data.paid is true

Keep placed['access'] with the order so a guest can open it again. The server only marks an order paid when the payment provider confirms it.

Coupons, gift cards and points are POST /cart/coupon, /cart/gift-card, /cart/points; each answers with the new cart.

7. Bookings and tickets

GET /booking/services/{slug} returns availability for the service's kind (slots for a date, class sessions, a room or hire quote for dates). POST /booking/services/{slug} books; a booking that must be paid comes back with next: 'checkout' and is in the cart.

Event tickets come from POST /events/{slug}/rsvp. Show check_in_code as a QR code at the door:

QrImageView(data: ticket['check_in_code'], size: 240)   // qr_flutter

8. Push

final token = await FirebaseMessaging.instance.getToken();
await dio.post('/me/devices', data: {'token': token, 'platform': Platform.isIOS ? 'ios' : 'android', 'topics': ['news']});
FirebaseMessaging.onMessageOpenedApp.listen((m) => router.go(m.data['path'] ?? '/'));

Order updates, replies about an order and chat answers arrive this way and in GET /me/notifications. Use the same Firebase project as the site's push settings.

9. Before the store

  • X-App-Version on every call, and the minimum versions set on the site.
  • Account deletion reachable inside the app.
  • Privacy and imprint links from /bootstrap in the app's settings screen.
  • App links: iOS team and bundle id, Android package and fingerprints in Settings → API, so links to the site open the app.