我想在我的颤振应用程序中使用共享首选项实现会话管理系统。对于依赖注入,我使用 GetIt 库。但是当我运行该应用程序时,它显示“颤振:创建会话时出错”“在构建 Builder(脏)时引发了以下 ArgumentError:无效参数(SharedPreferences 类型的对象未在 GetIt 中注册。您是否忘记传递实例名称? (你是不是不小心做了 GetIt sl=GetIt.instance(); 而不是 GetIt sl=GetIt.instance;)): SharedPreferences'
Session.dart
abstract class Session {
void storeLoginInfo(String accessToken);
bool isUserLoggedIn();
String getAccessToken();
void deleteLoginInfo();
}
SessionImpl.dart
class SessionImpl extends Session {
SharedPreferences sharedPref;
SessionImpl(SharedPreferences sharedPref) {
this.sharedPref = sharedPref;
}
@override
void storeLoginInfo(String accessToken) {
sharedPref.setBool('login_status', true);
sharedPref.setString('access_token', accessToken);
}
@override
bool isUserLoggedIn() {
final isLoggedIn = sharedPref.getBool('login_status') ?? false;
return isLoggedIn;
}
@override
String getAccessToken() {
return sharedPref.getString('access_token') ?? "";
}
@override
void deleteLoginInfo() {
if (sharedPref.containsKey('login_status')) sharedPref.remove('login_status');
if (sharedPref.containsKey('access_token')) sharedPref.remove('access_token');
}
}
ServiceLocator.dart
final serviceLocator = GetIt.instance;
Future<void> initDependencies() async {
_initSharedPref();
_initSession();
}
Future<void> _initSharedPref() async {
SharedPreferences sharedPref = await SharedPreferences.getInstance();
serviceLocator.registerSingleton<SharedPreferences>(sharedPref);
}
void _initSession() {
serviceLocator.registerLazySingleton<Session>(() => SessionImpl(serviceLocator()));
}
main.dart
void main() async {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations(
[DeviceOrientation.portraitUp, DeviceOrientation.portraitDown],
);
await initDependencies();
runApp(MyApp());
}