import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'base_stateful_page.dart'; import 'empty_controller.dart'; /* * 页面的基类,StatefulWidget 类型 * 选择性使用,如果想要在 BaseStatefulPage 的 子State中使用 Controller 就可以用。 * 如果没有传Key,则自动管理Key */ abstract class BaseState, C extends GetxController> extends State { C? _controller; C get controller => _controller ?? EmptyController() as C; @override void initState() { _createController(); super.initState(); } @override void dispose() { Get.delete(tag: widget.key?.toString()); super.dispose(); } void _createController() { try { _controller = GetInstance().find(tag: widget.key?.toString()); } catch (e) { _controller = null; } } //创建自动绑定Controller的GetBuilder GetBuilder autoCtlGetBuilder({ required Widget Function(C controller) builder, final Object? id, //Controller根据id来刷新指定的GetBuilder区域 final bool autoRemove = true, final bool global = true, final bool assignId = false, final void Function(GetBuilderState state)? initState, final void Function(GetBuilderState state)? dispose, final void Function(GetBuilderState state)? didChangeDependencies, }) { assert(_controller != null, "controller不能为空,请在 BaseState 与 BaseStatefulPage 中指定正确的泛型自动初始化"); return GetBuilder( init: _controller, tag: widget.key?.toString(), builder: builder, ); } }