getx icon indicating copy to clipboard operation
getx copied to clipboard

“Getx Controller Error: ‘AppClient?’ not found in Flutter”

Open Sokojiji opened this issue 1 year ago • 1 comments

I’m encountering an issue with my Flutter application using Getx for state management. The error message is 'AppClient?' not found. You need to call "Get.put(AppClient?())" or "Get.lazyPut(()=>AppClient?())".

Here is the Dart code in question:

main.dart

Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
init(); // replace dep.init() with init()
runApp(const MyApp());
}

void init() {
Get.lazyPut(() => AppClient());
Get.lazyPut(() => PopularProductRepo(
apiClient: Get.find(),
appClient: Get.find(),
));
Get.lazyPut(() => PopularProductController(
popularProductRepo: Get.find(),
appClient: Get.find(),
));
}

 class MyApp extends StatelessWidget {
 const MyApp({super.key});

// This widget is the root of your application.
 @override
 Widget build(BuildContext context) {
 Get.find<PopularProductController>().getPopularProductList();
 return GetMaterialApp(
  initialBinding: InitialBinding(), // add this line
  title: 'Flutter Demo',
  theme: ThemeData(
    primarySwatch: Colors.blue,
    ),
   home: RecommendedFoodDetail(),
  );
  }
}

here is the dependecies.dart

Future<void> init() async {
//api client
Get.lazyPut(() => ApiClient(appBaseUrl: "https://mvs.bslmeiyu.com"));
//repos
Get.lazyPut(() => PopularProductRepo(apiClient: Get.find(),appClient: Get.find(), //use a default value if null
));
//controllers
Get.lazyPut(() => PopularProductController(popularProductRepo: Get.find(),appClient: Get.find(),
));
}

class AppClient {
}
//or

  class PopularProductRepo {
  final ApiClient apiClient;
  final AppClient appClient; //make this parameter required

 PopularProductRepo({
  required this.apiClient, //use the required keyword
  required this.appClient, //use the required keyword
});
}

I addressed the issue by creating a file named initial_bindings.dart in the lib folder. Then added the snippet to it, Then in main.dart, added this line("initialBinding: InitialBinding(),") into the GetMaterialApp to no avail.

Sokojiji avatar Mar 04 '24 17:03 Sokojiji

According to the error, you declared the type in your dependency injection as a Nullable.

Get.find() will get exactly the type you determined, which means you cannot declare variables as nullable, and inject it into the constructor with Get.find(). Look in your code for something like:

AppClient? appClient;

jonataslaw avatar Mar 12 '24 08:03 jonataslaw