I am trying to use binding class to inject dependecies into my flutters application but for some reason its not working as i expected
binding class
class LibraryHomeBinding extends Bindings {
@override
void dependencies() {
Get.put(LibraryHomeController(), tag: 'home');
}
}
controller class
class LibraryHomeController extends GetxController {
@override
void onInit() {
print('initilizing');
super.onInit();
}
@override
void onReady() {
print('Controller ready');
super.onReady();
}
@override
void onClose() {
print('Controller closing');
super.onClose();
}
}
home
class LibraryHome extends StatelessWidget {
LibraryHome({super.key, required this.title});
final String title;
final libraryHomeBinding = Get.find(tag: 'home');
...
}
main
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return GetMaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: lightTheme,
getPages: [
GetPage(
name: '/home',
page: () => LibraryHome(title: 'Library'),
binding: LibraryHomeBinding(),
)
],
initialRoute: '/home',
);
}
}
i am getting this error
""dynamic" not found. You need to call "Get.put(dynamic())" or "Get.lazyPut(()=>dynamic())""
CodePudding user response:
when calling the Get.find()
you specified the tag, but you didn't specify the type, Getx
use the type and tag to generate a consistent key to get what you want so you need to do this :
final libraryHomeBinding = Get.find<LibraryHomeController>(tag: 'home');
or
final LibraryHomeController libraryHomeBinding = Get.find(tag: 'home');
now it will find it.
CodePudding user response:
on the binding class i think using extends is not quite right but use instead with/implements
class LibraryHomeBinding with Bindings {
@override
void dependencies() {
/// use lazy put
Get.lazyPut(LibraryHomeController(),fenix: true,tag: 'home');
}
}
then on the controller do it like this
class LibraryHomeController extends GetxController {
final findBind = Get.find<LibraryHomeController>( tag: "home");
@override
void onInit() {
print('initilizing');
super.onInit();
}
}