base_stateless_page.dart 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import 'package:flutter/material.dart';
  2. import 'package:get/get.dart';
  3. import 'empty_controller.dart';
  4. import 'global_key_factory.dart';
  5. /*
  6. * 页面的基类,StatelessWidget 类型
  7. * 只用于路由中定义的页面,如果是自定义布局或者PageView的子页面则无需继承
  8. * 如果没有传Key,则自动管理Key
  9. */
  10. abstract class BaseStatelessPage<C extends GetxController> extends StatelessWidget {
  11. BaseStatelessPage({Key? key}) : super(key: key ?? GlobalKeyFactory.createGlobalKey()) {
  12. _createController();
  13. }
  14. bool _initStatePerformed = false;
  15. C? _controller;
  16. C get controller => _controller ?? EmptyController() as C;
  17. void _createController() {
  18. try {
  19. _controller = GetInstance().put<C>(createRawController(), tag: key?.toString());
  20. } catch (e) {
  21. _controller = null;
  22. }
  23. }
  24. C createRawController();
  25. @protected
  26. Widget buildWidget(BuildContext context);
  27. void initState();
  28. @override
  29. Widget build(BuildContext context) {
  30. if (!_initStatePerformed) {
  31. initState();
  32. _initStatePerformed = true;
  33. }
  34. return buildWidget(context);
  35. }
  36. //创建自动绑定Controller的GetBuilder
  37. GetBuilder<C> autoCtlGetBuilder({
  38. required Widget Function(C controller) builder,
  39. final Object? id, //Controller根据id来刷新指定的GetBuilder区域
  40. final bool autoRemove = true,
  41. final bool global = true,
  42. final bool assignId = false,
  43. final void Function(GetBuilderState<C> state)? initState,
  44. final void Function(GetBuilderState<C> state)? dispose,
  45. final void Function(GetBuilderState<C> state)? didChangeDependencies,
  46. }) {
  47. assert(_controller != null, "controller不能为空,请在 BaseState 与 BaseStatefulPage 中指定正确的泛型自动初始化");
  48. return GetBuilder<C>(
  49. init: _controller,
  50. tag: key?.toString(),
  51. builder: builder,
  52. );
  53. }
  54. }