i get the error Unhandled Exception: "dynamic" not found. You need to call "Get.put(dynamic())" or "Get.lazyPut(()=>dynamic())" when i call the authController, below is my code.
if (Get.find<AuthController>().isLoggedIn()) {
//statements
}
my init function
Future init() async {
// Core
final sharedPreferences = await SharedPreferences.getInstance();
Get.lazyPut(() => sharedPreferences);
Get.lazyPut(() => ApiClient(
appBaseUrl: AppConstants.BASE_URL,
));
// Repository
Get.lazyPut(() => AuthRepo(apiClient:Get.find(), sharedPreferences: Get.find()));
// controller
Get.lazyPut(() => AuthController(authRepo: Get.find()));
}
main method
void main() async{
await di.init();
runApp(
child: MyApp(),
),
);
}
2
Answers
Getx
has this great feature which isGet.find()
, that finds the dependency you injected, but like in your example, you have multiple dependencies, let’s takesharedPreferences
andAuthController
and we tried to find them, so we did:on the code above, by logic it’s just the same thing, same function is called, but we want that each one will find a specific dependency, so how
Getx
manages to know exactly what you want with code ?it’s with objects types, you need to specify a generic
Type
for each dependency soGetx
will search for the right dependency with thatType
, otherwise, it will just take the default type given to it, which is thedynamic
type and this what causes the error.so in your case, instead of just typing:
You need to specify the dependency generic
Type
:and so on, you need to specify the generic
Type
in all of them to avoid getting exceptions like this every time.Note:
only
Get.find()
requires setting aType
generic to it,Get.put()
andGet.lazyPut()
can be specified byType
also but it’s fine to not set them.You are calling Get.find before Get.put.
Get.put instantiates the instance while Get.find tries to find it, so assure that the instance is created before you use Get.find.