I'm trying bloctesting for my project and getting the following error:
'package:get_it/get_it_impl.dart': Failed assertion: line 372 pos 7: 'instanceFactory != null': Object/factory with type SharedPreferences is not registered inside GetIt.
(Did you accidentally do GetIt sl=GetIt.instance(); instead of GetIt sl=GetIt.instance;
Did you forget to register it?)
Below are my sharedpreferences injection files
shared_preference_injection_configuration.dart
import 'package:get_it/get_it.dart';
import 'package:injectable/injectable.dart';
import 'package:shared_preferences/shared_preferences.dart';
final GetIt getIt = GetIt.instance;
@injectableInit
Future<void> configureInjection(String env) async {
await $initGetIt(getIt, environment: env);
}
Future<void> initDependencies() async {
await _initSharedPref();
}
Future<void> _initSharedPref() async {
final SharedPreferences sharedPref = await SharedPreferences.getInstance();
getIt.registerSingleton<SharedPreferences>(sharedPref);
}
shared_preference_injection.dart
import 'package:injectable/injectable.dart';
import 'package:shared_preferences/shared_preferences.dart';
@module
abstract class InjectionModule {
//injecting third party libraries
@preResolve
Future<SharedPreferences> get prefs => SharedPreferences.getInstance();
}
Below lies the main method.It already has the configureinjection and initdependencies method but still gives me the same error.
main.dart
void main() async {
// Make sure all bindings are loaded for easy localization
WidgetsFlutterBinding.ensureInitialized();
await EasyLocalization.ensureInitialized();
await configureInjection(Environment.prod);
await initDependencies();
// ignore: always_specify_types
EasyLocalization.logger.enableBuildModes = [];
// Load bloc Observer for debugging
BlocOverrides.runZoned(() => SimpleBlocObserver());
// Define main breakpoints for responsive_builder
ResponsiveSizingConfig.instance.setCustomBreakpoints(
const ScreenBreakpoints(desktop: PDesktopSize, tablet: PTabletSize, watch: PWatchSize),
);
// Set default locale to german style
// Intl.defaultLocale = 'de_DE';
// Load bloc Observer for debugging
runZonedGuarded(
() async {
await BlocOverrides.runZoned(
// Main Entry Point for our application
// Translations wrapping around the whole app and start the structure for Cecht
() async => runApp(
EasyLocalization(
supportedLocales: const <Locale>[
Locale('en'),
Locale('de'),
],
path: 'assets/translations_v5',
fallbackLocale: const Locale('de'),
child: MyApp(),
),
),
blocObserver: SimpleBlocObserver(),
);
},
(Object error, StackTrace stackTrace) => Logger().logWarning('${error.toString()} $stackTrace'),
);
}
Okay so when you're doing blocTesting then you need to register your packages again in the setup function in it which is in the case you are using getit for dependency injection.