|
| 1 | +import 'package:quick_actions/quick_actions.dart'; |
| 2 | + |
| 3 | +/// Shortcut type identifier for the "add weight" home-screen app shortcut. |
| 4 | +const String addWeightShortcutType = 'action_add_weight'; |
| 5 | + |
| 6 | +/// Manages Android home-screen app shortcuts (long-press on the launcher icon). |
| 7 | +/// |
| 8 | +/// Bridges the native shortcut callback to the Flutter UI: when the app is |
| 9 | +/// cold-started via a shortcut it stores a pending request that the home page |
| 10 | +/// consumes once it is ready; when the app is already running it forwards the |
| 11 | +/// tap to a registered live [handler]. |
| 12 | +class QuickActionsService { |
| 13 | + /// Returns the singleton instance. |
| 14 | + factory QuickActionsService() => _instance; |
| 15 | + QuickActionsService._(); |
| 16 | + static final QuickActionsService _instance = QuickActionsService._(); |
| 17 | + |
| 18 | + final QuickActions _quickActions = const QuickActions(); |
| 19 | + |
| 20 | + /// Whether an "add weight" shortcut was triggered but not yet handled. |
| 21 | + bool pendingAddWeight = false; |
| 22 | + |
| 23 | + /// Live handler invoked when a shortcut is tapped while the app is running. |
| 24 | + void Function()? _handler; |
| 25 | + |
| 26 | + /// Initialise the platform channel and register the shortcut callback. |
| 27 | + /// |
| 28 | + /// Call once during app start-up. On cold start the callback fires before |
| 29 | + /// any UI exists, so the request is stored in [pendingAddWeight]. |
| 30 | + void init() { |
| 31 | + _quickActions.initialize((String type) { |
| 32 | + if (type != addWeightShortcutType) { |
| 33 | + return; |
| 34 | + } |
| 35 | + final void Function()? handler = _handler; |
| 36 | + if (handler != null) { |
| 37 | + handler(); |
| 38 | + } else { |
| 39 | + pendingAddWeight = true; |
| 40 | + } |
| 41 | + }); |
| 42 | + } |
| 43 | + |
| 44 | + /// Register the home-screen shortcut items. |
| 45 | + /// |
| 46 | + /// Call from a context where a localized [title] is available so the entry |
| 47 | + /// in the launcher menu is translated. |
| 48 | + Future<void> setShortcuts({required String title}) async { |
| 49 | + await _quickActions.setShortcutItems(<ShortcutItem>[ |
| 50 | + ShortcutItem( |
| 51 | + type: addWeightShortcutType, |
| 52 | + localizedTitle: title, |
| 53 | + icon: 'ic_shortcut_add', |
| 54 | + ), |
| 55 | + ]); |
| 56 | + } |
| 57 | + |
| 58 | + /// Register a live [handler] for shortcut taps and flush any pending request. |
| 59 | + void registerHandler(void Function() handler) { |
| 60 | + _handler = handler; |
| 61 | + if (pendingAddWeight) { |
| 62 | + pendingAddWeight = false; |
| 63 | + handler(); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + /// Remove the live handler, e.g. when the consuming widget is disposed. |
| 68 | + void unregisterHandler() { |
| 69 | + _handler = null; |
| 70 | + } |
| 71 | +} |
0 commit comments