Reputation: 55
I have a configuration of nested GetX controllers, which represent my data model. They look like this (I shortened the code to show only controllers structure):
class AppController extends GetxController {
final package = PackageController().obs;
void openPackage() {
// some code with unzipping, parsing and eventually creating instance of PackageController
package.value = packageController;
}
}
.
class PackageController extends GetxController {
final rounds = RxList<RoundController>();
void addRound() {
rounds.add(RoundController());
}
void deleteRound(int index) {
rounds.removeAt(index);
}
}
.
class RoundController extends GetxController {
final themes = RxList<ThemeController>();
void addTheme() {
themes.add(ThemeController());
}
void deleteTheme(int index) {
themes.removeAt(index);
}
}
It goes deeper, but that's enough for understanding. In my UI widgets I access AppController with final store = Get.put(AppController());
and through it I have access to any nested controller I need.
Now to the problem: lifecycle methods like onInit()
are called only for AppController()
and not for any of the nested ones. So, is there some trick I need to know, or I use GetX in a wrong way, or what?
Upvotes: 0
Views: 999
Reputation: 5020
The lifecycle methods are called only if the GetX dependency injection system creates the instances. Therefore you need to create these instances with Get.put()
or Get.lazyPut()
like this:
rounds.add(Get.lazyPut(()=>RoundController()));
themes.add(Get.lazyPut(()=> ThemeController()));
Updated Answer:
Yeah. Get.lazyPut()
won't add the controller to the list as it returns void
.
So you need to actually use Get.create()
for different instances:
Get.create(()=>RoundController());
Get.create(()=> ThemeController());
And then:
rounds.add(Get.find<RoundController>());
themes.add(Get.find<ThemeController>());
Upvotes: 1