'GetIt - Instance shows as registered but then it become unregistered
So GetIt is acting a bit weird and I couldn't figure out why! After calling the setupLocator() in main function. I wanted to check if an instance if registered or not; but for some reason the isRegistered functions returns True in MyApp class but False in AuthenticationScreen!
Future<void> setupLocator() async {
// Use Cases
sl.registerLazySingleton(() => LogoutCurrentUser(repository: sl()));
sl.registerLazySingleton(() => LoginWithEmailAndPassword(repository: sl()));
sl.registerLazySingleton(() => SignupWithEmailAndPassword(repository: sl()));
// Repositories
sl.registerLazySingleton<AuthenticationRepository>(
() => AuthenticationRepositoryImpl(
networkInfo: sl(),
hiveDataSource: sl(),
firebaseDataSource: sl(),
),
);
// Other services...
}
I'm calling the setup function in main:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Hive.initFlutter();
Hive.registerAdapter(UserAdapter());
// Here!
await di.setupLocator();
runApp(
DevicePreview(
enabled: false,
builder: (_) => const MyApp(),
),
);
}
But now something weird happens! I did a check if LoginWithEmailAndPassword() isRegistered in MyApp widget it returns True, but in another screen AuthenticationScreen it returns False!
This is MyApp Screen:
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final _navigatorKey = GlobalKey<NavigatorState>();
NavigatorState get _navigator => _navigatorKey.currentState!;
@override
Widget build(BuildContext context) {
// Returns True
print(sl.isRegistered<LoginWithEmailAndPassword>());
return BlocProvider(
create: (context) => AuthenticationBloc(
authenticationRepository: sl<AuthenticationRepository>(),
logoutCurrentUser: sl<LogoutCurrentUser>(),
),
child: MaterialApp(
navigatorKey: _navigatorKey,
useInheritedMediaQuery: true,
locale: DevicePreview.locale(context),
builder: (context, child) {
return BlocListener<AuthenticationBloc, AuthenticationState>(
listenWhen: (previous, current) =>
previous.status != current.status,
listener: (context, state) {
switch (state.status) {
case AuthenticationStatus.authenticated:
_navigator.pushNamedAndRemoveUntil(
HomeScreen.sRoute,
(route) => false,
);
break;
case AuthenticationStatus.unauthenticated:
_navigator.pushNamedAndRemoveUntil(
AuthenticationScreen.sRoute,
(route) => false,
);
break;
default:
_navigator.pushNamedAndRemoveUntil(
AuthenticationScreen.sRoute,
(route) => false,
);
}
},
child: DevicePreview.appBuilder(context, child),
);
},
title: 'App',
onGenerateRoute: RouteGenerator.onGenerateRoute,
initialRoute: '/',
),
);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
