base_state.dart 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import 'package:flutter/material.dart';
  2. import 'package:get/get.dart';
  3. import 'base_stateful_page.dart';
  4. import 'empty_controller.dart';
  5. /*
  6. * 页面的基类,StatefulWidget 类型
  7. * 选择性使用,如果想要在 BaseStatefulPage 的 子State中使用 Controller 就可以用。
  8. * 如果没有传Key,则自动管理Key
  9. */
  10. abstract class BaseState<T extends BaseStatefulPage<C>, C extends GetxController> extends State<T> {
  11. C? _controller;
  12. C get controller => _controller ?? EmptyController() as C;
  13. @override
  14. void initState() {
  15. _createController();
  16. super.initState();
  17. }
  18. @override
  19. void dispose() {
  20. Get.delete<C>(tag: widget.key?.toString());
  21. super.dispose();
  22. }
  23. void _createController() {
  24. try {
  25. _controller = GetInstance().find<C>(tag: widget.key?.toString());
  26. } catch (e) {
  27. _controller = null;
  28. }
  29. }
  30. //创建自动绑定Controller的GetBuilder
  31. GetBuilder<C> autoCtlGetBuilder({
  32. required Widget Function(C controller) builder,
  33. final Object? id, //Controller根据id来刷新指定的GetBuilder区域
  34. final bool autoRemove = true,
  35. final bool global = true,
  36. final bool assignId = false,
  37. final void Function(GetBuilderState<C> state)? initState,
  38. final void Function(GetBuilderState<C> state)? dispose,
  39. final void Function(GetBuilderState<C> state)? didChangeDependencies,
  40. }) {
  41. assert(_controller != null, "controller不能为空,请在 BaseState 与 BaseStatefulPage 中指定正确的泛型自动初始化");
  42. return GetBuilder<C>(
  43. init: _controller,
  44. tag: widget.key?.toString(),
  45. builder: builder,
  46. );
  47. }
  48. }