base_vm.dart 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. /// 自动导入ValueNotifier拓展
  2. export 'package:lszlgl/ext/value_notifier_ext.dart';
  3. ///
  4. /// VM基类
  5. abstract class BaseVM {
  6. /// 是否被销毁
  7. bool _dispose = false;
  8. get isDispose => _dispose;
  9. /// 销毁时回调方法
  10. void dispose() {
  11. _dispose = true;
  12. }
  13. }
  14. ///
  15. /// 数据状态装饰类
  16. ///
  17. /// ```
  18. /// 简单使用方法:
  19. /// // 数据
  20. /// var user = DataStatusModel<UserBean>();
  21. /// user = user.empty();
  22. /// user = user.loading();
  23. /// user = user.success(UserBean());
  24. /// user = user.error('网络异常');
  25. /// // 组件
  26. /// setState({});
  27. /// switch (user.status) {
  28. /// ...
  29. /// }
  30. /// ```
  31. ///
  32. /// ```
  33. /// 配合ValueNotifierExt使用:
  34. /// // 数据
  35. /// final user = DataStatusModel<UserBean>().notifier<DataStatusModel<UserBean>>();
  36. /// user.update(user.value.empty());
  37. /// user.update(user.value.loading());
  38. /// user.update(user.value.success(UserBean()));
  39. /// user.update(user.value.error('网络异常'));
  40. /// // 组件
  41. /// user.builder((v) {
  42. /// switch (v.status) {
  43. /// ...
  44. /// }
  45. /// }
  46. /// ```
  47. class DataStatusModel<T> {
  48. /// 数据状态
  49. DataStatus status;
  50. /// 数据内容
  51. T? data;
  52. /// 错误信息
  53. Object? errorData;
  54. DataStatusModel({
  55. this.status = DataStatus.empty,
  56. this.data,
  57. this.errorData,
  58. });
  59. /// 加载中
  60. DataStatusModel<T> loading({T? data, Object? error}) => DataStatusModel<T>(
  61. status: DataStatus.loading,
  62. data: data ?? this.data,
  63. errorData: error ?? this.errorData,
  64. );
  65. /// 加载成功
  66. DataStatusModel<T> success({T? data, Object? error}) => DataStatusModel<T>(
  67. status: DataStatus.success,
  68. data: data ?? this.data,
  69. errorData: error ?? this.errorData,
  70. );
  71. /// 无数据
  72. DataStatusModel<T> empty({T? data, Object? error}) => DataStatusModel<T>(
  73. data: data ?? this.data,
  74. errorData: error ?? this.errorData,
  75. );
  76. /// 加载失败
  77. DataStatusModel<T> error({T? data, Object? error}) => DataStatusModel<T>(
  78. status: DataStatus.error,
  79. data: data ?? this.data,
  80. errorData: error ?? this.errorData,
  81. );
  82. }
  83. /// 数据状态
  84. enum DataStatus {
  85. /// 无数据
  86. empty,
  87. /// 加载中
  88. loading,
  89. /// 加载成功
  90. success,
  91. /// 加载失败
  92. error,
  93. }