Skip to content

Instantly share code, notes, and snippets.

@felipebueno
Last active July 24, 2024 00:02
Show Gist options
  • Save felipebueno/d14857004a9244c14e1859de4e78c110 to your computer and use it in GitHub Desktop.
Save felipebueno/d14857004a9244c14e1859de4e78c110 to your computer and use it in GitHub Desktop.
Flutter web update alert
// See https://x.com/whoisgraham/status/1815843202647089352
// for context
Future<void> maybeUpdate() async {
if (!kIsWeb) {
return;
}
try {
final response = await Dio().get( // We could use dart http instead of dio
'https://YOUR_BASE_URL/version.json?${Random().nextDouble()}', // Random double on each request to avoid cache
);
if (response.data == null) {
return;
}
dynamic data = response.data;
if (response.data is String) {
data = jsonDecode(response.data);
}
final package = (await PackageInfo.fromPlatform());
final currentVersion = package.version;
final currentBuildNumber = package.buildNumber;
if ((currentVersion.isNotEmpty && currentBuildNumber.isNotEmpty) &&
(currentVersion != data['version'] ||
currentBuildNumber != data['build_number'])) {
final appVersion = 'v${data['version']}.${data['build_number']}';
await showDecisionDialog( // This is an abstraction on a regular AlertDialog with Yes No actions
title: 'Update Available',
msg: 'Would you like to update the app to the new version $appVersion?',
onYesPressed: window.location.reload,
);
}
} catch (e, st) {
// Only capture the exception. No need to show an error to the user
captureException(e, st);
}
}
// My suggestion on how to use it is to put it inside a StatefullWidget
// you use on every page so the maybeUpdate fn will always be called
// Something like this:
// class _NotificationsButtonState extends State<NotificationsButton> {
// late Timer _timer;
// double _key = Random().nextDouble();
// @override
// void initState() {
// super.initState();
// _timer = Timer.periodic(
// const Duration(minutes: 5),
// (timer) async {
// setState(() {
// _key = Random().nextDouble();
// });
// try {
// if (kIsWeb) {
// await maybeUpdate();
// }
// } catch (e, st) {
// captureException(e, st);
// }
// },
// );
// }
// @override
// void dispose() {
// _timer.cancel();
// super.dispose();
// }
//
// ...
//
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment