You can use following very simple class to get the SharedPreferences instance without await:
import 'package:shared_preferences/shared_preferences.dart';
class SharedPrefs {
static late final SharedPreferences instance;
static Future<SharedPreferences> init() async =>
instance = await SharedPreferences.getInstance();
}
- Initiliaze the
instance maybe in main() function, as follows:
void main() async {
// Required for async calls in `main`
WidgetsFlutterBinding.ensureInitialized();
// Initialize SharedPrefs instance.
await SharedPrefs.init();
runApp(MyApp());
}
- Access methods on
SharedPrefs.instance, for e.g.:
final someString = SharedPrefs.instance.getString('someString') ?? 'defaultValue';
await SharedPrefs.instance.setBool('someBool', true);
Extra:
If preferred, one can further abstract by redefining these methods (getBool, setString, etc.) or defining new methods (getUser, setUser, setAccessToken etc.) in SharedPrefs class itself and making instance a private field like _instance.
One such example is as follows:
// Getter
static bool? getBool(String key) => _instance.getBool(key);
// Setter
static Future<bool> setBool(String key, bool value) => _instance.setBool(key, value);
// More abstraction
static const _kAccessToken = 'accessToken';
static Future<bool> setAccessToken(String value) => _instance.setString(_kAccessToken, value);
static String? getAccessToken() => _instance.getString(_kAccessToken);
After this, one can simply call these methods, as follows:
final someBool = SharedPrefs.getBool('someBool') ?? false;
await SharedPrefs.setBool('someBool', someBool);
final accessToken = SharedPrefs.getAccessToken();