mirror of
https://github.com/flutter/samples.git
synced 2026-06-25 07:38:26 +00:00
## Description Migrated `SharedPreferences` usage in `compass_app` to `SharedPreferencesAsync` to align with the latest `shared_preferences` recommendations. ### Changes made * Replaced `SharedPreferences.getInstance()` usages * Updated async preference reads with awaited getters * Migrated token persistence logic * Updated test setup preference clearing logic Fixes #2720 ## Pre-launch Checklist * [x] I read the [[Flutter Style Guide](https://github.com/flutter/flutter/blob/master/docs/contributing/Style-guide-for-Flutter-repo.md)] *recently*, and have followed its advice. * [x] I signed the [[CLA](https://cla.developers.google.com/)]. * [x] I read the [[Contributors Guide](https://github.com/flutter/samples/blob/main/CONTRIBUTING.md)]. * [ ] I have added sample code updates to the [[changelog](https://chatgpt.com/CHANGELOG.md)]. * [ ] I updated/added relevant documentation (doc comments with `///`). <!-- Links --> [Flutter Style Guide]: https://github.com/flutter/flutter/blob/master/docs/contributing/Style-guide-for-Flutter-repo.md [CLA]: https://cla.developers.google.com/ [Discord]: https://github.com/flutter/flutter/blob/master/docs/contributing/Chat.md [Contributors Guide]: https://github.com/flutter/samples/blob/main/CONTRIBUTING.md [changelog]: ../CHANGELOG.md Co-authored-by: Eric Windmill <eric@ericwindmill.com>
48 lines
1.3 KiB
Dart
48 lines
1.3 KiB
Dart
// Copyright 2024 The Flutter team. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
|
|
import 'package:logging/logging.dart';
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
|
|
import '../../utils/result.dart';
|
|
|
|
class SharedPreferencesService {
|
|
static const _tokenKey = 'TOKEN';
|
|
final _log = Logger('SharedPreferencesService');
|
|
|
|
Future<Result<String?>> fetchToken() async {
|
|
try {
|
|
final sharedPreferences = SharedPreferencesAsync();
|
|
|
|
_log.finer('Got token from SharedPreferences');
|
|
|
|
return Result.ok(await sharedPreferences.getString(_tokenKey));
|
|
} on Exception catch (e) {
|
|
_log.warning('Failed to get token', e);
|
|
return Result.error(e);
|
|
}
|
|
}
|
|
|
|
Future<Result<void>> saveToken(String? token) async {
|
|
try {
|
|
final sharedPreferences = SharedPreferencesAsync();
|
|
|
|
if (token == null) {
|
|
_log.finer('Removed token');
|
|
|
|
await sharedPreferences.remove(_tokenKey);
|
|
} else {
|
|
_log.finer('Replaced token');
|
|
|
|
await sharedPreferences.setString(_tokenKey, token);
|
|
}
|
|
|
|
return const Result.ok(null);
|
|
} on Exception catch (e) {
|
|
_log.warning('Failed to set token', e);
|
|
return Result.error(e);
|
|
}
|
|
}
|
|
}
|