Store secrets securely and handle app lifecycle events.
Secure Storage
flutter pub add flutter_secure_storage// lib/services/secure_storage.dart
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
class SecureStorageService {
static const FlutterSecureStorage _storage = FlutterSecureStorage(
aOptions: AndroidOptions(
encryptedSharedPreferences: true,
keyCipherAlgorithm: KeyCipherAlgorithm.AES_GCM,
storageCipherAlgorithm: StorageCipherAlgorithm.AES_GCM,
),
iOptions: IOSOptions(
accessibility: KeychainAccessibility.first_unlock_this_device,
),
);
// Save string
static Future<void> write(String key, String value) async {
await _storage.write(key: key, value: value);
}
// Read string
static Future<String?> read(String key) async {
return await _storage.read(key: key);
}
// Delete key
static Future<void> delete(String key) async {
await _storage.delete(key: key);
}
// Delete all
static Future<void> deleteAll() async {
await _storage.deleteAll();
}
// Read all
static Future<Map<String, String>> readAll() async {
return await _storage.readAll();
}
// Check if key exists
static Future<bool> containsKey(String key) async {
return await _storage.containsKey(key: key);
}
}
// Token storage
class TokenStorage {
static const String _accessTokenKey = 'access_token';
static const String _refreshTokenKey = 'refresh_token';
static const String _tokenExpiryKey = 'token_expiry';
static Future<void> saveTokens({
required String accessToken,
required String refreshToken,
required int expiresInSeconds,
}) async {
final expiry = DateTime.now().add(Duration(seconds: expiresInSeconds)).toIso8601String();
await Future.wait([
SecureStorageService.write(_accessTokenKey, accessToken),
SecureStorageService.write(_refreshTokenKey, refreshToken),
SecureStorageService.write(_tokenExpiryKey, expiry),
]);
}
static Future<String?> getAccessToken() async {
return await SecureStorageService.read(_accessTokenKey);
}
static Future<String?> getRefreshToken() async {
return await SecureStorageService.read(_refreshTokenKey);
}
static Future<DateTime?> getExpiry() async {
final expiryStr = await SecureStorageService.read(_tokenExpiryKey);
if (expiryStr == null) return null;
return DateTime.parse(expiryStr);
}
static Future<bool> isTokenExpired() async {
final expiry = await getExpiry();
if (expiry == null) return true;
return DateTime.now().isAfter(expiry);
}
static Future<void> clearTokens() async {
await Future.wait([
SecureStorageService.delete(_accessTokenKey),
SecureStorageService.delete(_refreshTokenKey),
SecureStorageService.delete(_tokenExpiryKey),
]);
}
}App Lifecycle
import 'package:flutter/widgets.dart';
class LifecycleManager {
static final LifecycleManager _instance = LifecycleManager._internal();
factory LifecycleManager() => _instance;
LifecycleManager._internal();
final List<AppLifecycleListener> _listeners = [];
void addListener(AppLifecycleListener listener) {
_listeners.add(listener);
}
void removeListener(AppLifecycleListener listener) {
_listeners.remove(listener);
}
}
// AppLifecycleListener (Flutter 3.10+)
class AppLifecycleHandler extends StatefulWidget {
final Widget child;
const AppLifecycleHandler({super.key, required this.child});
@override
State<AppLifecycleHandler> createState() => _AppLifecycleHandlerState();
}
class _AppLifecycleHandlerState extends State<AppLifecycleHandler> with WidgetsBindingObserver {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
print('App lifecycle: $state');
switch (state) {
case AppLifecycleState.resumed:
// App visible and interactive
_onResume();
break;
case AppLifecycleState.inactive:
// App in transition (phone call, split screen)
_onInactive();
break;
case AppLifecycleState.paused:
// App not visible
_onPause();
break;
case AppLifecycleState.detached:
// Engine destroyed
_onDetach();
break;
case AppLifecycleState.hidden:
// App hidden (iOS background, Android stopped)
_onHidden();
break;
}
}
void _onResume() {
// Refresh data, reconnect sockets, resume timers
print('App resumed');
}
void _onInactive() {
// Save draft, pause animations
print('App inactive');
}
void _onPause() {
// Save state, disconnect sockets, stop timers
print('App paused');
}
void _onHidden() {
// App hidden but not destroyed
print('App hidden');
}
void _onDetach() {
// Clean up
print('App detached');
}
@override
Widget build(BuildContext context) {
return widget.child;
}
}
// Modern AppLifecycleListener (Flutter 3.10+)
class ModernLifecycleHandler extends StatelessWidget {
final Widget child;
const ModernLifecycleHandler({super.key, required this.child});
@override
Widget build(BuildContext context) {
return AppLifecycleListener(
onResume: () => print('Resumed'),
onInactive: () => print('Inactive'),
onPause: () => print('Paused'),
onDetach: () => print('Detached'),
onHide: () => print('Hidden'),
onShow: () => print('Shown'),
onRestart: () => print('Restarted'),
child: child,
);
}
}Background Execution
// lib/services/background_service.dart
import 'package:flutter_background_service/flutter_background_service.dart';
import 'package:flutter_background_service_android/flutter_background_service_android.dart';
class BackgroundService {
static final FlutterBackgroundService _service = FlutterBackgroundService();
static Future<void> initialize() async {
await _service.configure(
androidConfiguration: AndroidConfiguration(
onStart: onStart,
autoStart: true,
isForegroundMode: true,
notificationChannelId: 'background_service',
initialNotificationTitle: 'Background Service',
initialNotificationContent: 'Running in background',
foregroundServiceTypes: [AndroidForegroundType.dataSync],
),
iosConfiguration: IosConfiguration(
autoStart: true,
onForeground: onStart,
onBackground: onIosBackground,
),
);
}
static void startService() {
_service.invoke('start');
}
static void stopService() {
_service.invoke('stop');
}
@pragma('vm:entry-point')
static void onStart(ServiceInstance service) async {
if (service is AndroidServiceInstance) {
service.setForegroundNotificationInfo(
title: 'Background Service',
content: 'Syncing data...',
);
}
service.on('stop').listen((event) {
service.stopSelf();
});
// Do periodic work
Timer.periodic(Duration(minutes: 15), (timer) async {
if (!(await _service.isRunning())) {
timer.cancel();
return;
}
// Perform background sync
await _performBackgroundSync();
});
}
@pragma('vm:entry-point')
static Future<bool> onIosBackground(ServiceInstance service) async {
return true;
}
static Future<void> _performBackgroundSync() async {
// Sync data with server
print('Background sync executed');
}
}flutter pub add flutter_background_service
flutter pub add flutter_background_service_android<!-- android/app/src/main/AndroidManifest.xml -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />Try It
Store tokens in secure storage. Add lifecycle handler. Test: login → kill app → reopen → tokens persist. Background: start service → kill app → verify sync runs.
flutter pub add flutter_secure_storage
flutter pub add flutter_background_service flutter_background_service_androidBuild secure auth with background sync
- Implement TokenStorage with flutter_secure_storage
- Add AppLifecycleListener for token refresh on resume
- Set up background service for periodic data sync
- Handle token expiry and auto-refresh
- Test on physical device (background works differently on simulators)
Use flutter_secure_storage for tokens (Keychain/Keystore). AppLifecycleListener handles resume/pause/detach. Background execution limited - use flutter_background_service with foreground service on Android. iOS has stricter background limits.
Resources
- flutter_secure_storage: https://pub.dev/packages/flutter_secure_storage
- AppLifecycleListener: https://api.flutter.dev/flutter/widgets/AppLifecycleListener-class.html
- Background Service: https://pub.dev/packages/flutter_background_service