DEV Community

Cover image for update_gate: forced and optional update prompts for Flutter that fail open
Abdeldjalil Chougui
Abdeldjalil Chougui

Posted on Edited on Originally published at abdeldjalilchougui.biz

update_gate: forced and optional update prompts for Flutter that fail open

Sooner or later a mobile app needs to tell its users to update. Sometimes it is a suggestion: a new version is out, here is what changed. Sometimes it is a requirement: the old version talks to an API that no longer exists, and letting people in would only show them errors.

The mechanism is simple to describe. The app asks a server "what is the minimum version, and what is the latest?", compares that with its own version, and shows a dialog or a blocking page. The dangerous part is the blocking page. If the rule is wrong, a typo in the version string or a half-edited JSON file can lock every user out of the app, including the ones who are fully up to date. And you cannot fix a locked-out app with an update the users cannot be told about.

update_gate is a Flutter package for these prompts. It works with any source of version rules: your own JSON endpoint, Remote Config or a database. And it fails open, so a broken rule never locks users out.

What it does

Version parsing. AppVersion parses semver-like strings (1.2, 5, v1.2.3, 1.2.3+45, 1.0.0-beta.2+7) and orders them, including numeric build numbers.

A policy object. UpdatePolicy holds the minimum required version, the latest version, the store URL, a "remind me later" interval, a title and a message per locale, and per-platform overrides. It reads a simple JSON format.

A pure decision function. UpdateDecision.evaluate returns none, optional or forced. Missing data, junk versions or any error give none.

Pluggable sources. UpdatePolicySource is an interface with one fetch() method. The package includes JsonUrlSource (built on package:http, with an injectable client) and StaticSource.

The UpdateGate widget.

  • Forced: a full-screen page that back navigation cannot pop (PopScope).
  • Optional: a dismissible dialog, shown again only after the remind interval, with a pluggable RemindLaterStore.
  • It opens the store through your callback, so there is no url_launcher dependency.
  • It reads the running version through your callback, so there is no package_info_plus dependency.

Texts. Default texts come in English, French and Arabic, and RTL layouts follow the ambient Directionality. You can replace the forced page and the dialog with your own builders.

How to use it

Add it from GitHub:

dependencies:
  update_gate:
    git: https://github.com/AbdeldjalilChougui/update_gate
Enter fullscreen mode Exit fullscreen mode

Then wrap your home page. package_info_plus and url_launcher are your app's dependencies, not this package's:

import 'package:flutter/material.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:update_gate/update_gate.dart';
import 'package:url_launcher/url_launcher.dart';

MaterialApp(
  home: UpdateGate(
    source: JsonUrlSource(Uri.parse('https://example.com/app/update.json')),
    currentVersion: () async {
      final info = await PackageInfo.fromPlatform();
      return '${info.version}+${info.buildNumber}';
    },
    onOpenStore: (decision) async {
      final url = decision.storeUrl;
      if (url != null) {
        await launchUrl(url, mode: LaunchMode.externalApplication);
      }
    },
    child: const HomePage(),
  ),
);
Enter fullscreen mode Exit fullscreen mode

The gate needs a Navigator. As home it finds it by itself. If you put it in MaterialApp.builder, above the navigator, pass the same navigatorKey to both.

The JSON your endpoint returns looks like this:

{
  "min_required_version": "1.2.0",
  "latest_version": "1.4.0+52",
  "store_url": "https://play.google.com/store/apps/details?id=my.app",
  "remind_after_hours": 24,
  "title": {"en": "New version", "fr": "Nouvelle version"},
  "message": {
    "en": "Faster sync and bug fixes.",
    "fr": "Synchronisation plus rapide et corrections.",
    "ar": "مزامنة أسرع وإصلاحات."
  },
  "platforms": {
    "ios": {
      "min_required_version": "1.3.0",
      "store_url": "https://apps.apple.com/app/id000000000"
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Every field is optional. title and message may be plain strings. Locale keys are matched exactly (fr_CA or fr-CA), then by language, then default, then en. Without a match, the built-in text is used. The platform keys are android, ios, macos, windows, linux, fuchsia and web.

The rules

You can also decide without the widget and block the app your own way:

final decision = UpdateDecision.evaluate(
  currentVersion: '1.2.0+12',
  policy: const UpdatePolicy(minRequiredVersion: '1.3.0'),
  platform: UpdatePlatform.android,
);
if (decision.isForced) {
  // Block the app your own way.
}
Enter fullscreen mode Exit fullscreen mode

The decision table is short enough to remember:

  • current < min: forced.
  • min <= current < latest: optional.
  • current >= latest, or only min set and current >= min: none.
  • No policy, or a junk or empty current version: none.
  • A configured min or latest that is junk: none, for both rules.
  • Neither min nor latest set: none.
  • Since 0.2.0, one explicit exception: force_update: true in the policy (or a 426 from your API, see below) gives forced whatever the versions.

The three lines before the last are the "fail open" part. When the package cannot be sure, it lets the user in. The only thing that overrides that is the server saying so explicitly.

Other sources and custom UI

Any backend fits behind UpdatePolicySource. The README has adapters for Firebase Remote Config and Supabase, and a RemindLaterStore on shared_preferences so that "Later" survives a restart. It marks all three clearly as sketches that were not compiled in the package, so treat them as a starting point and test them in your app.

For the UI, you can change single strings or replace the widgets:

UpdateGate(
  // ...
  strings: UpdateGateStrings.fr.copyWith(later: 'Pas maintenant'),
  forcedBuilder: (context, prompt) => MyForcedPage(
    title: prompt.title,
    message: prompt.message,
    onUpdate: prompt.onUpdate,
  ),
  optionalBuilder: (context, prompt) => AlertDialog(
    title: Text(prompt.title),
    actions: [
      TextButton(onPressed: prompt.onLater, child: Text(prompt.strings.later)),
      TextButton(onPressed: prompt.onUpdate, child: Text(prompt.strings.update)),
    ],
  ),
  child: const HomePage(),
);
Enter fullscreen mode Exit fullscreen mode

The forced route is wrapped in PopScope(canPop: false) whatever the builder returns.

Things to know

  • When the gate checks. With a plain source (a JSON URL, Remote Config) it checks once, when it is first built, and does not re-check on app resume. With ResponseSignalSource (added in 0.2.0, below) it checks again every time a stronger signal arrives.
  • A forced page is a pushed route. Code that later calls Navigator.pop directly, not maybePop, can still remove it.
  • One remind interval per policy. There is only one "remind me later" interval per policy (24 hours by default), and a newer latest version always resets it.
  • The default remind store forgets on restart. Persist it with any key-value store if you want "Later" to last.
  • Non-numeric build metadata is ignored when comparing. Something like +exp.sha.5114f85 is kept but does not take part in the ordering.
  • The Arabic and French default texts are hand-written. The README asks you to review them with a native speaker for your audience.

Update: forcing from your API responses (0.2.0)

A reader described a neat alternative: let the rule ride on normal API responses instead of a separate endpoint. Version 0.2.0 adds that as ResponseSignalSource. Your own http.Client wrapper or dio interceptor reports each response to it:

final signals = ResponseSignalSource(base: JsonUrlSource(policyUrl));

// in your HTTP layer, for every response:
signals.observeHeaders(response.statusCode, response.headers);

UpdateGate(source: signals, /* ... */ child: const HomePage());
Enter fullscreen mode Exit fullscreen mode
  • A 426 Upgrade Required forces the update at once, even in the middle of a session.
  • A minimum-version header (X-Min-App-Version by default) above the installed version forces it too; equal or lower does nothing.
  • A missing or unreadable header is ignored, so the app still fails open.
  • The gate listens to the source and re-checks only when the signal gets stronger, and it never stacks a second forced page.
  • With a base source, optional updates, the store link and the texts still come from your usual policy.

Why I built it

The README states the two ideas the package is built around in its first paragraph: it works with any source of version rules, and it fails open.

The first is about dependencies. An update prompt is a small feature, and it should not decide which backend you use, nor pull a version plugin and a URL plugin into every app. So the source is an interface, and the running version and the store link go through two callbacks. If your rules live in a JSON file on your own server, that is enough.

The second is about the worst case. A forced-update screen is the one screen in an app that is designed to stop people. I wanted the decision to be a pure function with a written table, where every doubtful input (no policy, an unreadable version, an error while fetching) ends in none. A missed prompt is a small problem. A locked-out user base is not.

Get the code

The source, the JSON format, the adapter sketches and the tests are on GitHub: https://github.com/AbdeldjalilChougui/update_gate. It is MIT licensed. Issues and pull requests are welcome.


Originally published at abdeldjalilchougui.biz.

Top comments (2)

Collapse
 
beusebiu profile image
Eusebiu Balan •

Mine fails open too, but the rule rides on normal API responses instead of its own endpoint. The blocking screen only shows when a response says so: an HTTP 426, or a minimum-version header above the installed version. A header it can't parse is ignored, and no response at all means no screen.

Server errors get a separate screen, and only a 401 ever signs anyone out.

Collapse
 
abdeldjalilchougui profile image
Abdeldjalil Chougui •

Nice, that's a clean approach: no extra endpoint, and the server can force the update on any request, mid-session. I like that an unparseable header is just ignored; same spirit as failing open here. update_gate starts from the other end: the app fetches a policy (a JSON URL, Remote Config, Supabase…) and evaluates it, which works before the first API call and also covers optional updates with a "remind me later" interval and localized messages. The two could combine well: an HTTP interceptor that turns a 426 or a min-version header into a policy for the gate. That would be a nice source to add.