1 Get.put() Get.find()
父界面负责 put 放入 controller
子界面负责 find 取出 controller
import 'package:get/get.dart';class CountController extends GetxController {final count = 0.obs;add() => count.value++;@overridevoid onInit() {super.onInit();print("onInit");}@overridevoid onClose() {super.onClose();print("clode");}}
class StateDependencyPutFindView extends StatelessWidget {StateDependencyPutFindView({Key? key}) : super(key: key);final controller = Get.put<CountController>(CountController());@overrideWidget build(BuildContext context) {return Scaffold(appBar: AppBar(title: Text("Dependency"),),body: Center(child: Column(children: [GetX<CountController>(init: controller,initState: (_) {},builder: (_) {return Text('value -> ${_.count}');},),Divider(),// 按钮ElevatedButton(onPressed: () {controller.add();},child: Text('add'),),// 跳转ElevatedButton(onPressed: () {Get.to(() => NextPageView());},child: Text('next page'),),],),),);}}
class NextPageView extends StatelessWidget {NextPageView({Key? key}) : super(key: key);final controller = Get.find<CountController>();@overrideWidget build(BuildContext context) {return Scaffold(appBar: AppBar(title: Text("NextPage"),),body: Center(child: Column(children: [GetX<CountController>(init: controller,initState: (_) {},builder: (_) {return Text('value -> ${_.count}');},),Divider(),],),),);}}
2 Get.lazyput() GetView
lazyput, 会先注册回调函数, 当调用Get.find()时自动触发该回调, put一个controller实例
同上
import 'package:get/get.dart';import 'controller.dart';class DependencyLazyPutBinding implements Bindings {@overridevoid dependencies() {Get.lazyPut<CountController>(() => CountController());}}
class StateDependencyLazyPutView extends StatelessWidget {StateDependencyLazyPutView({Key? key}) : super(key: key);@overrideWidget build(BuildContext context) {return Scaffold(appBar: AppBar(title: Text("Dependency - LazyPut"),),body: Center(child: Column(children: [GetX<CountController>(init: Get.find<CountController>(),initState: (_) {},builder: (_) {return Text('value -> ${_.count}');},),Divider(),// 按钮ElevatedButton(onPressed: () {Get.find<CountController>().add();},child: Text('add'),),// 跳转ElevatedButton(onPressed: () {Get.to(NextPageView());},child: Text('Next GetView Page'),),],),),);}}
class NextPageView extends GetView<CountController> {NextPageView({Key? key}) : super(key: key);@overrideWidget build(BuildContext context) {return Scaffold(appBar: AppBar(title: Text("GetView Page"),),body: Center(child: Column(children: [Obx(() => Text('value -> ${controller.count}')),Divider(),// 按钮ElevatedButton(onPressed: () {controller.add();},child: Text('add'),),],),),);}}
GetPage(name: AppRoutes.Lazy,page: () => StateDependencyLazyPutView(),binding: DependencyLazyPutBinding())
