Home > Enterprise >  You need to call "Get.put(dynamic())" or "Get.lazyPut(()=>dynamic())"
You need to call "Get.put(dynamic())" or "Get.lazyPut(()=>dynamic())"

Time:11-25

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(),
  ),
  );
 }

CodePudding user response:

Getx has this great feature which is Get.find(), that finds the dependency you injected, but like in your example, you have multiple dependencies, let's take sharedPreferences and AuthController and we tried to find them, so we did:

Get.find();
Get.find();

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 so Getx will search for the right dependency with that Type, otherwise, it will just take the default type given to it, which is the dynamic type and this what causes the error.

so in your case, instead of just typing:

Get.find(); // Getx: how I would know what should I return?
Get.find(); // Getx: how I would know what should I return?

You need to specify the dependency generic Type:

Get.find<AuthController>(); // return AuthController dependency 
Get.find<SharedPreferences>(); // return SharedPreferences dependency

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 a Type generic to it, Get.put() and Get.lazyPut() can be specified by Type also but it's fine to not set them.

CodePudding user response:

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.

  • Related