element.dart 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. import 'package:flutter/material.dart';
  2. /// 要素模型
  3. class DocumentElement {
  4. final String id;
  5. final ElementType type;
  6. final String label;
  7. final String value;
  8. final Offset? position; // 在文档中的位置
  9. final String? documentId;
  10. final Map<String, dynamic>? metadata;
  11. DocumentElement({
  12. required this.id,
  13. required this.type,
  14. required this.label,
  15. required this.value,
  16. this.position,
  17. this.documentId,
  18. this.metadata,
  19. });
  20. /// 从JSON创建
  21. factory DocumentElement.fromJson(Map<String, dynamic> json) {
  22. return DocumentElement(
  23. id: json['id'] as String,
  24. type: ElementType.values.firstWhere(
  25. (e) => e.toString().split('.').last == json['type'],
  26. orElse: () => ElementType.other,
  27. ),
  28. label: json['label'] as String,
  29. value: json['value'] as String,
  30. position: json['position'] != null
  31. ? Offset(
  32. (json['position'] as Map)['x'] as double,
  33. (json['position'] as Map)['y'] as double,
  34. )
  35. : null,
  36. documentId: json['documentId'] as String?,
  37. metadata: json['metadata'] as Map<String, dynamic>?,
  38. );
  39. }
  40. /// 转换为JSON
  41. Map<String, dynamic> toJson() {
  42. return {
  43. 'id': id,
  44. 'type': type.toString().split('.').last,
  45. 'label': label,
  46. 'value': value,
  47. 'position':
  48. position != null ? {'x': position!.dx, 'y': position!.dy} : null,
  49. 'documentId': documentId,
  50. 'metadata': metadata,
  51. };
  52. }
  53. /// 复制并更新
  54. DocumentElement copyWith({
  55. String? id,
  56. ElementType? type,
  57. String? label,
  58. String? value,
  59. Offset? position,
  60. String? documentId,
  61. Map<String, dynamic>? metadata,
  62. }) {
  63. return DocumentElement(
  64. id: id ?? this.id,
  65. type: type ?? this.type,
  66. label: label ?? this.label,
  67. value: value ?? this.value,
  68. position: position ?? this.position,
  69. documentId: documentId ?? this.documentId,
  70. metadata: metadata ?? this.metadata,
  71. );
  72. }
  73. /// 显示文本
  74. String get displayText => '$label: $value';
  75. }
  76. /// 要素类型
  77. enum ElementType {
  78. amount, // 金额
  79. company, // 公司
  80. person, // 人名
  81. location, // 地名
  82. date, // 日期
  83. other, // 其他
  84. }
  85. extension ElementTypeExtension on ElementType {
  86. String get label {
  87. switch (this) {
  88. case ElementType.amount:
  89. return '金额';
  90. case ElementType.company:
  91. return '公司';
  92. case ElementType.person:
  93. return '人名';
  94. case ElementType.location:
  95. return '地名';
  96. case ElementType.date:
  97. return '日期';
  98. case ElementType.other:
  99. return '其他';
  100. }
  101. }
  102. }