mirror of https://github.com/flutter/samples.git
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
42 lines
1.3 KiB
42 lines
1.3 KiB
// 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 = await SharedPreferences.getInstance();
|
|
_log.finer('Got token from SharedPreferences');
|
|
return Result.ok(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 = await SharedPreferences.getInstance();
|
|
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);
|
|
}
|
|
}
|
|
}
|