get_binding_widget.dart 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. import 'package:flutter/material.dart';
  2. import 'package:get/get.dart';
  3. /*
  4. //使用示例,单个Controller
  5. final logic = Get.put(TestLogic());
  6. @override
  7. Widget build(BuildContext context) {
  8. return GetBindWidget(
  9. bind: logic,
  10. child: Container(),
  11. );
  12. }
  13. //使用示例,多个Controller
  14. final logicOne = Get.put(TestLogic(), tag: 'one');
  15. final logicTwo = Get.put(TestLogic());
  16. final logicThree = Get.put(TestLogic(), tag: 'three');
  17. @override
  18. Widget build(BuildContext context) {
  19. return GetBindWidget(
  20. binds: [logicOne, logicTwo, logicThree],
  21. tags: ['one', '', 'three'],
  22. child: Container(),
  23. );
  24. }
  25. */
  26. /// 可以自定义绑定用于GetX框架无法正常回收Controller的场景,包裹根视图,设置bind属性,手动绑定到Controller,
  27. /// 当页面退出的时候指定解绑Controller
  28. class GetBindWidget extends StatefulWidget {
  29. const GetBindWidget({
  30. Key? key,
  31. this.bind,
  32. this.tag,
  33. this.binds,
  34. this.tags,
  35. required this.child,
  36. }) : assert(
  37. binds == null || tags == null || binds.length == tags.length,
  38. 'The binds and tags arrays length should be equal\n'
  39. 'and the elements in the two arrays correspond one-to-one',
  40. ),
  41. super(key: key);
  42. final GetxController? bind;
  43. final String? tag;
  44. final List<GetxController>? binds;
  45. final List<String>? tags;
  46. final Widget child;
  47. @override
  48. _GetBindWidgetState createState() => _GetBindWidgetState();
  49. }
  50. class _GetBindWidgetState extends State<GetBindWidget> {
  51. @override
  52. Widget build(BuildContext context) {
  53. return widget.child;
  54. }
  55. @override
  56. void dispose() {
  57. _closeGetXController();
  58. _closeGetXControllers();
  59. super.dispose();
  60. }
  61. ///Close GetxController bound to the current modules
  62. void _closeGetXController() {
  63. if (widget.bind == null) {
  64. return;
  65. }
  66. var key = widget.bind.runtimeType.toString() + (widget.tag ?? '');
  67. GetInstance().delete(key: key);
  68. }
  69. ///Batch close GetxController bound to the current modules
  70. void _closeGetXControllers() {
  71. if (widget.binds == null) {
  72. return;
  73. }
  74. for (var i = 0; i < widget.binds!.length; i++) {
  75. var type = widget.binds![i].runtimeType.toString();
  76. if (widget.tags == null) {
  77. GetInstance().delete(key: type);
  78. } else {
  79. var key = type + (widget.tags?[i] ?? '');
  80. GetInstance().delete(key: key);
  81. }
  82. }
  83. }
  84. }