Use a simple Service Locator for Dart get_it. You will have many such cases when you have to have a global object to work with other than SharedPreferences too.
The first step is to add dependencies for get_it. Just go to a link,
and flollow steps below to set shared preferences below up.
Your SharedPreferences will be
import 'package:flutter/cupertino.dart';
import 'package:shared_preferences/shared_preferences.dart';
class SharedPrefs extends ChangeNotifier {
SharedPreferences? _prefsInstance;
SharedPrefs() {
_init();
}
Future<void> _init() async {
_prefsInstance = await SharedPreferences.getInstance();
getIt.signalReady(this);
}
bool getBool(String key, [bool elseValue = false]) {
return _prefsInstance?.getBool(key) ?? elseValue;
}
Future<bool> setBool(String key, bool value) async {
return _prefsInstance?.setBool(key, value) ?? Future.value(false);
}
}
In main.dart
import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:yourpackage/shared_prefs.dart';
import 'app.dart';
GetIt getIt = GetIt.instance;
void main() {
WidgetsFlutterBinding.ensureInitialized();
getIt.registerSingleton(SharedPrefs(), signalsReady: true);
runApp(const App());
}
Anywhere you need shared preferences you call it
final authenticated = getIt<SharedPrefs>().getBool('key_auth');