DEV Community

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

Posted 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.

The last three lines are the "fail open" part. When the package cannot be sure, it lets the user in.

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

  • The gate checks once, when it is first built. It does not re-check on app resume.
  • 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.

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 (0)