-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathjson_editor_flutter.dart
More file actions
1328 lines (1234 loc) · 40.7 KB
/
Copy pathjson_editor_flutter.dart
File metadata and controls
1328 lines (1234 loc) · 40.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
library json_editor_flutter;
import 'dart:convert';
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
const _space = 18.0;
const _textStyle = TextStyle(fontSize: 16);
const _options = Icon(Icons.more_horiz, size: 16);
const _expandIconWidth = 10.0;
const _rowHeight = 30.0;
const _popupMenuHeight = 30.0;
const _popupMenuItemPadding = 20.0;
const _textSpacer = SizedBox(width: 5);
const _newKey = "new_key_added";
const _downArrow = SizedBox(
width: _expandIconWidth,
child: Icon(CupertinoIcons.arrowtriangle_down_fill, size: 14),
);
const _rightArrow = SizedBox(
width: _expandIconWidth,
child: Icon(CupertinoIcons.arrowtriangle_right_fill, size: 14),
);
const _newDataValue = {
_OptionItems.string: "",
_OptionItems.bool: false,
_OptionItems.num: 0,
};
bool _enableMoreOptions = true;
bool _enableKeyEdit = true;
bool _enableValueEdit = true;
enum _OptionItems { map, list, string, bool, num, delete }
enum _SearchActions { next, prev }
/// Supported editors for JSON Editor.
enum Editors { tree, text }
/// Edit your JSON object with this Widget. Create, edit and format objects
/// using this user friendly widget.
class JsonEditor extends StatefulWidget {
/// JSON can be edited in two ways, Tree editor or text editor. You can disable
/// either of them.
///
/// When UI editor is active, you can disable adding/deleting keys by using
/// [enableMoreOptions]. Editing keys and values can also be disabled by using
/// [enableKeyEdit] and [enableValueEdit].
///
/// When text editor is active, it will simply ignore [enableMoreOptions],
/// [enableKeyEdit] and [enableValueEdit].
///
/// [duration] is the debounce time for [onChanged] function. Defaults to
/// 500 milliseconds.
///
/// [editors] is the supported list of editors. First element will be
/// used as default editor. Defaults to `[Editors.tree, Editors.text]`.
const JsonEditor({
super.key,
required this.json,
required this.onChanged,
this.duration = const Duration(milliseconds: 500),
this.enableMoreOptions = true,
this.enableKeyEdit = true,
this.enableValueEdit = true,
this.editors = const [Editors.tree, Editors.text],
this.themeColor,
this.actions = const [],
this.enableHorizontalScroll = false,
this.searchDuration = const Duration(milliseconds: 500),
this.hideEditorsMenuButton = false,
this.expandedObjects = const [],
}) : assert(editors.length > 0, "editors list cannot be empty");
/// JSON string to be edited.
final String json;
/// Callback function that will be called with the new [dynamic] data.
final ValueChanged<dynamic> onChanged;
/// Debounce duration for [onChanged] function.
final Duration duration;
/// Enables more options like adding or deleting data. Defaults to `true`.
final bool enableMoreOptions;
/// Enables editing of keys. Defaults to `true`.
final bool enableKeyEdit;
/// Enables editing of values. Defaults to `true`.
final bool enableValueEdit;
/// Theme color for the editor. Changes the border color and header color.
final Color? themeColor;
/// List of supported editors. First element will be used as default editor.
final List<Editors> editors;
/// A list of Widgets to display in a row at the end of header.
final List<Widget> actions;
/// Enables horizontal scroll for the tree view. Defaults to `false`.
final bool enableHorizontalScroll;
/// Debounce duration for search function.
final Duration searchDuration;
/// Hides the option of changing editor. Defaults to `false`.
final bool hideEditorsMenuButton;
/// [expandedObjects] refers to the objects that will be expanded by
/// default. Index can be provided when the data is a List.
///
/// Examples:
/// ```dart
/// data = {
/// "hobbies": ["Reading books", "Playing Cricket"],
/// "education": [
/// {"name": "Bachelor of Engineering", "marks": 75},
/// {"name": "Master of Engineering", "marks": 72},
/// ],
/// }
/// ```
///
/// For the given data
/// 1. To expand education pass => `["education"]`
/// 2. To expand hobbies and education pass => `["hobbies", "education"]`
/// 3. To expand the first element (index 0) of education list, this means
/// we need to expand education too. In this case you need not to pass
/// "education" separately. Just pass a list of all nested objects =>
/// `[["education", 0]]`
///
/// ```dart
/// JsonEditor(
/// expandedObjects: const [
/// "hobbies",
/// ["education", 0] // expands nested object in education
/// ],
/// onChanged: (_) {},
/// json: jsonEncode(data),
/// )
/// ```
final List expandedObjects;
@override
State<JsonEditor> createState() => _JsonEditorState();
}
class _JsonEditorState extends State<JsonEditor> {
Timer? _timer;
Timer? _searchTimer;
late dynamic _data;
late final _themeColor = widget.themeColor ?? Theme.of(context).primaryColor;
late Editors _editor = widget.editors.first;
bool _onError = false;
bool? allExpanded;
late final _controller = TextEditingController()
..text = _stringifyData(_data, 0, true);
late final _scrollController = ScrollController();
final _matchedKeys = <String, bool>{};
final _matchedKeysLocation = <List>[];
int? _focusedKey;
int? _results;
late final _expandedObjects = <String, bool>{
["object"].toString(): true,
if (widget.expandedObjects.isNotEmpty) ...getExpandedParents(),
};
Map<String, bool> getExpandedParents() {
final map = <String, bool>{};
for (var key in widget.expandedObjects) {
if (key is List) {
final newExpandList = ["object", ...key];
for (int i = newExpandList.length - 1; i > 0; i--) {
map[newExpandList.toString()] = true;
newExpandList.removeLast();
}
} else {
map[["object", key].toString()] = true;
}
}
return map;
}
void callOnChanged() {
if (_timer?.isActive ?? false) _timer?.cancel();
_timer = Timer(widget.duration, () {
widget.onChanged(jsonDecode(jsonEncode(_data)));
});
}
void parseData(String value) {
if (_timer?.isActive ?? false) _timer?.cancel();
_timer = Timer(widget.duration, () {
try {
_data = jsonDecode(value);
widget.onChanged(_data);
setState(() {
_onError = false;
});
} catch (_) {
setState(() {
_onError = true;
});
}
});
}
void copyData() async {
await Clipboard.setData(
ClipboardData(text: jsonEncode(_data)),
);
}
bool updateParentObjects(List newExpandList) {
bool needsRebuilding = false;
for (int i = newExpandList.length - 1; i >= 0; i--) {
if (_expandedObjects[newExpandList.toString()] == null) {
_expandedObjects[newExpandList.toString()] = true;
needsRebuilding = true;
}
newExpandList.removeLast();
}
return needsRebuilding;
}
void findMatchingKeys(data, String text, List nestedParents) {
if (data is Map) {
final keys = data.keys.toList();
for (var key in keys) {
final keyName = key.toString();
if (keyName.toLowerCase().contains(text)) {
_results = _results! + 1;
_matchedKeys[keyName] = true;
_matchedKeysLocation.add([...nestedParents, key]);
}
if (data[key] is Map) {
findMatchingKeys(data[key], text, [...nestedParents, key]);
} else if (data[key] is List) {
findMatchingKeys(data[key], text, [...nestedParents, key]);
}
}
} else if (data is List) {
for (int i = 0; i < data.length; i++) {
final item = data[i];
if (item is Map) {
findMatchingKeys(item, text, [...nestedParents, i]);
} else if (item is List) {
findMatchingKeys(item, text, [...nestedParents, i]);
}
}
}
}
void onSearch(String text) {
if (_searchTimer?.isActive ?? false) _searchTimer?.cancel();
_searchTimer = Timer(widget.searchDuration, () async {
_matchedKeys.clear();
_matchedKeysLocation.clear();
_focusedKey = null;
if (text.isEmpty) {
setState(() {
_results = null;
});
} else {
_results = 0;
findMatchingKeys(_data, text.toLowerCase(), ["object"]);
setState(() {});
if (_matchedKeys.isNotEmpty) {
_focusedKey = 0;
scrollTo(0);
}
}
});
}
int getOffset(List toFind) {
int offset = 1;
bool keyFound = false;
void calculateOffset(data, List parents, List toFind) {
if (keyFound) return;
if (data is Map) {
for (var entry in data.entries) {
if (keyFound) return;
offset++;
final newList = [...parents, entry.key];
if (entry.key == toFind.last &&
newList.toString() == toFind.toString()) {
keyFound = true;
return;
}
if (entry.value is Map || entry.value is List) {
if (_expandedObjects[newList.toString()] == true && !keyFound) {
calculateOffset(entry.value, newList, toFind);
}
}
}
} else if (data is List) {
for (int i = 0; i < data.length; i++) {
if (keyFound) return;
offset++;
if (data[i] is Map || data[i] is List) {
final newList = [...parents, i];
if (_expandedObjects[newList.toString()] == true && !keyFound) {
calculateOffset(data[i], newList, toFind);
}
}
}
}
}
calculateOffset(_data, ["object"], toFind);
return offset;
}
void scrollTo(int index) {
final toFind = [..._matchedKeysLocation[index]];
final needsRebuilding = updateParentObjects(
[..._matchedKeysLocation[index]]..removeLast(),
);
if (needsRebuilding) setState(() {});
Future.delayed(const Duration(milliseconds: 150), () {
_scrollController.animateTo(
(getOffset(toFind) * _rowHeight) - 90,
duration: const Duration(milliseconds: 200),
curve: Curves.easeInOut,
);
});
}
void onSearchAction(_SearchActions action) {
if (_matchedKeys.isEmpty) return;
if (action == _SearchActions.next) {
if (_focusedKey != null &&
_matchedKeysLocation.length - 1 > _focusedKey!) {
_focusedKey = _focusedKey! + 1;
} else {
_focusedKey = 0;
}
} else {
if (_focusedKey != null && _focusedKey! > 0) {
_focusedKey = _focusedKey! - 1;
} else {
_focusedKey = _matchedKeysLocation.length - 1;
}
}
scrollTo(_focusedKey!);
}
void expandAllObjects(data, List expandedList) {
if (data is Map) {
for (var entry in data.entries) {
if (entry.value is Map || entry.value is List) {
final newList = [...expandedList, entry.key];
_expandedObjects[newList.toString()] = true;
expandAllObjects(entry.value, newList);
}
}
} else if (data is List) {
for (int i = 0; i < data.length; i++) {
if (data[i] is Map || data[i] is List) {
final newList = [...expandedList, i];
_expandedObjects[newList.toString()] = true;
expandAllObjects(data[i], newList);
}
}
}
}
Widget wrapWithHorizontolScroll(Widget child) {
if (widget.enableHorizontalScroll) {
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: child,
);
}
return child;
}
@override
void initState() {
super.initState();
_data = jsonDecode(widget.json);
_enableMoreOptions = widget.enableMoreOptions;
_enableKeyEdit = widget.enableKeyEdit;
_enableValueEdit = widget.enableValueEdit;
}
@override
void didUpdateWidget(covariant oldWidget) {
print("didUpdateWidget json ${widget.json}");
print("didUpdateWidget data: $_data");
_data = jsonDecode(widget.json);
super.didUpdateWidget(oldWidget);
}
@override
void dispose() {
_timer?.cancel();
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
print("json ${widget.json}");
print("data: $_data");
return DecoratedBox(
decoration: BoxDecoration(
border: Border.all(
width: _onError ? 2 : 1,
color: _onError ? Colors.red : _themeColor,
),
),
child: SizedBox(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
DecoratedBox(
decoration: BoxDecoration(
color: _themeColor,
border: _onError
? const Border(
bottom: BorderSide(color: Colors.red, width: 2),
)
: null),
child: Padding(
padding: const EdgeInsets.symmetric(
vertical: 6,
horizontal: 10,
),
child: Row(
children: [
if (!widget.hideEditorsMenuButton)
PopupMenuButton<Editors>(
initialValue: _editor,
tooltip: 'Change editor',
padding: EdgeInsets.zero,
onSelected: (value) {
if (value == Editors.text) {
_controller.text = _stringifyData(_data, 0, true);
}
setState(() {
_editor = value;
});
},
position: PopupMenuPosition.under,
enabled: widget.editors.length > 1,
constraints: const BoxConstraints(
minWidth: 50,
maxWidth: 150,
),
itemBuilder: (context) {
return <PopupMenuEntry<Editors>>[
PopupMenuItem<Editors>(
height: _popupMenuHeight,
padding:
const EdgeInsets.symmetric(horizontal: 12),
enabled: widget.editors.contains(Editors.tree),
value: Editors.tree,
child: const Text("Tree"),
),
PopupMenuItem<Editors>(
height: _popupMenuHeight,
padding:
const EdgeInsets.symmetric(horizontal: 12),
enabled: widget.editors.contains(Editors.text),
value: Editors.text,
child: const Text("Text"),
),
];
},
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(_editor.name, style: _textStyle),
const Icon(Icons.arrow_drop_down, size: 20),
],
),
),
const Spacer(),
if (_editor == Editors.text) ...[
const SizedBox(width: 20),
InkWell(
onTap: () {
_controller.text = _stringifyData(_data, 0, true);
},
child: const Tooltip(
message: 'Format',
child: Icon(Icons.format_align_left, size: 20),
),
),
] else ...[
const SizedBox(width: 20),
if (_results != null) ...[
Text("$_results results"),
const SizedBox(width: 5),
],
_SearchField(onSearch, onSearchAction),
const SizedBox(width: 20),
InkWell(
onTap: () {
_expandedObjects[["object"].toString()] = true;
expandAllObjects(_data, ["object"]);
setState(() {});
},
child: const Tooltip(
message: 'Expand All',
child: Icon(Icons.expand, size: 20),
),
),
const SizedBox(width: 20),
InkWell(
onTap: () {
_expandedObjects.clear();
setState(() {});
},
child: const Tooltip(
message: 'Collapse All',
child: Icon(Icons.compress, size: 20),
),
),
],
const SizedBox(width: 20),
InkWell(
onTap: copyData,
child: const Tooltip(
message: 'Copy',
child: Icon(Icons.copy, size: 20),
),
),
if (widget.actions.isNotEmpty) const SizedBox(width: 20),
...widget.actions,
],
),
),
),
if (_editor == Editors.tree)
Expanded(
child: SingleChildScrollView(
controller: _scrollController,
physics: const ClampingScrollPhysics(),
child: wrapWithHorizontolScroll(
_Holder(
key: UniqueKey(),
data: _data,
keyName: "object",
paddingLeft: _space,
onChanged: callOnChanged,
parentObject: {"object": _data},
setState: setState,
matchedKeys: _matchedKeys,
allParents: const ["object"],
expandedObjects: _expandedObjects,
),
),
),
),
if (_editor == Editors.text)
Expanded(
child: TextFormField(
controller: _controller,
onChanged: parseData,
maxLines: null,
minLines: null,
expands: true,
textAlignVertical: TextAlignVertical.top,
decoration: const InputDecoration(
border: InputBorder.none,
contentPadding: EdgeInsets.only(
left: 5,
top: 8,
bottom: 8,
),
),
),
),
],
),
),
);
}
}
class _Holder extends StatefulWidget {
const _Holder({
super.key,
this.keyName,
required this.data,
required this.paddingLeft,
required this.onChanged,
required this.parentObject,
required this.setState,
required this.matchedKeys,
required this.allParents,
required this.expandedObjects,
});
final dynamic keyName;
final dynamic data;
final double paddingLeft;
final VoidCallback onChanged;
final dynamic parentObject;
final StateSetter setState;
final Map<String, bool> matchedKeys;
final List allParents;
final Map<String, bool> expandedObjects;
@override
State<_Holder> createState() => _HolderState();
}
class _HolderState extends State<_Holder> {
late bool isExpanded =
widget.expandedObjects[widget.allParents.toString()] == true;
void _toggleState() {
if (!isExpanded) {
widget.expandedObjects[widget.allParents.toString()] = true;
} else {
widget.expandedObjects.remove(widget.allParents.toString());
}
setState(() {
isExpanded = !isExpanded;
});
}
void onSelected(_OptionItems selectedItem) {
if (selectedItem == _OptionItems.delete) {
if (widget.parentObject is Map) {
widget.parentObject.remove(widget.keyName);
} else {
widget.parentObject.removeAt(widget.keyName);
}
widget.setState(() {});
} else if (selectedItem == _OptionItems.map) {
if (widget.data is Map) {
widget.data[_newKey] = {};
} else {
widget.data.add({});
}
setState(() {});
} else if (selectedItem == _OptionItems.list) {
if (widget.data is Map) {
widget.data[_newKey] = [];
} else {
widget.data.add([]);
}
setState(() {});
} else {
if (widget.data is Map) {
widget.data[_newKey] = _newDataValue[selectedItem];
} else {
widget.data.add(_newDataValue[selectedItem]);
}
setState(() {});
}
widget.onChanged();
}
void onKeyChanged(Object key) {
final val = widget.parentObject.remove(widget.keyName);
widget.parentObject[key] = val;
widget.onChanged();
widget.setState(() {});
}
void onValueChanged(Object value) {
widget.parentObject[widget.keyName] = value;
widget.onChanged();
}
Widget wrapWithColoredBox(Widget child, String key) {
if (widget.matchedKeys[key] == true) {
return ColoredBox(color: Colors.yellow, child: child);
}
return child;
}
@override
Widget build(BuildContext context) {
if (widget.data is Map) {
final mapWidget = <Widget>[];
final List keys = widget.data.keys.toList();
for (var key in keys) {
mapWidget.add(_Holder(
key: Key(key),
data: widget.data[key],
keyName: key,
onChanged: widget.onChanged,
parentObject: widget.data,
paddingLeft: widget.paddingLeft + _space,
setState: setState,
matchedKeys: widget.matchedKeys,
allParents: [...widget.allParents, key],
expandedObjects: widget.expandedObjects,
));
}
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
SizedBox(
height: _rowHeight,
child: Row(
children: [
const SizedBox(width: _expandIconWidth),
if (_enableMoreOptions) _Options<Map>(onSelected),
SizedBox(width: widget.paddingLeft),
InkWell(
hoverColor: Colors.transparent,
splashColor: Colors.transparent,
onTap: _toggleState,
child: isExpanded ? _downArrow : _rightArrow,
),
const SizedBox(width: _expandIconWidth),
if (_enableKeyEdit && widget.parentObject is! List) ...[
_ReplaceTextWithField(
key: Key(widget.keyName.toString()),
initialValue: widget.keyName,
isKey: true,
onChanged: onKeyChanged,
setState: setState,
isHighlighted:
widget.matchedKeys["${widget.keyName}"] == true,
),
_textSpacer,
Text(
"{${widget.data.length}}",
style: _textStyle,
),
] else
InkWell(
hoverColor: Colors.transparent,
splashColor: Colors.transparent,
onTap: _toggleState,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
wrapWithColoredBox(
Text("${widget.keyName}", style: _textStyle),
"${widget.keyName}",
),
_textSpacer,
Text("{${widget.data.length}}", style: _textStyle),
],
),
),
],
),
),
if (isExpanded)
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: mapWidget,
),
],
);
} else if (widget.data is List) {
final listWidget = <Widget>[];
for (int i = 0; i < widget.data.length; i++) {
listWidget.add(_Holder(
key: Key(i.toString()),
keyName: i,
data: widget.data[i],
onChanged: widget.onChanged,
parentObject: widget.data,
paddingLeft: widget.paddingLeft + _space,
setState: setState,
matchedKeys: widget.matchedKeys,
allParents: [...widget.allParents, i],
expandedObjects: widget.expandedObjects,
));
}
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
SizedBox(
height: _rowHeight,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(width: _expandIconWidth),
if (_enableMoreOptions) _Options<List>(onSelected),
SizedBox(width: widget.paddingLeft),
InkWell(
hoverColor: Colors.transparent,
splashColor: Colors.transparent,
onTap: _toggleState,
child: isExpanded ? _downArrow : _rightArrow,
),
const SizedBox(width: _expandIconWidth),
if (_enableKeyEdit && widget.parentObject is! List) ...[
_ReplaceTextWithField(
key: Key(widget.keyName.toString()),
initialValue: widget.keyName,
isKey: true,
onChanged: onKeyChanged,
setState: setState,
isHighlighted:
widget.matchedKeys["${widget.keyName}"] == true,
),
_textSpacer,
Text(
"[${widget.data.length}]",
style: _textStyle,
),
] else
InkWell(
hoverColor: Colors.transparent,
splashColor: Colors.transparent,
onTap: _toggleState,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
wrapWithColoredBox(
Text("${widget.keyName}", style: _textStyle),
"${widget.keyName}",
),
_textSpacer,
Text("[${widget.data.length}]", style: _textStyle),
],
),
),
],
),
),
if (isExpanded)
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: listWidget,
),
],
);
} else {
return SizedBox(
height: _rowHeight,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(width: _expandIconWidth),
if (_enableMoreOptions) _Options<String>(onSelected),
SizedBox(
width: widget.paddingLeft + (_expandIconWidth * 2),
),
Row(
mainAxisSize: MainAxisSize.min,
children: [
if (_enableKeyEdit) ...[
_ReplaceTextWithField(
key: Key(widget.keyName.toString()),
initialValue: widget.keyName,
isKey: true,
onChanged: onKeyChanged,
setState: setState,
isHighlighted:
widget.matchedKeys["${widget.keyName}"] == true,
),
const Text(' :', style: _textStyle),
] else
Row(
mainAxisSize: MainAxisSize.min,
children: [
wrapWithColoredBox(
Text("${widget.keyName}", style: _textStyle),
"${widget.keyName}",
),
_textSpacer,
const Text(" :", style: _textStyle),
],
),
_textSpacer,
if (_enableValueEdit) ...[
_ReplaceTextWithField(
key: UniqueKey(),
initialValue: widget.data,
onChanged: onValueChanged,
setState: setState,
),
_textSpacer,
] else ...[
Text(widget.data.toString(), style: _textStyle),
_textSpacer,
],
],
),
],
),
);
}
}
}
class _ReplaceTextWithField extends StatefulWidget {
const _ReplaceTextWithField({
super.key,
required this.initialValue,
required this.onChanged,
required this.setState,
this.isKey = false,
this.isHighlighted = false,
});
final dynamic initialValue;
final bool isKey;
final ValueChanged<Object> onChanged;
final StateSetter setState;
final bool isHighlighted;
@override
State<_ReplaceTextWithField> createState() => _ReplaceTextWithFieldState();
}
class _ReplaceTextWithFieldState extends State<_ReplaceTextWithField> {
late final _focusNode = FocusNode();
bool _isFocused = false;
bool _value = false;
String _text = "";
late final BoxConstraints _constraints;
void handleChange() {
if (!_focusNode.hasFocus) {
_text = _text.trim();
final val = num.tryParse(_text);
if (val == null) {
widget.onChanged(_text);
} else {
widget.onChanged(val);
}
setState(() {
_isFocused = false;
});
}
}
Widget wrapWithColoredBox(String keyName) {
if (widget.isHighlighted) {
return ColoredBox(
color: Colors.amber,
child: Text(keyName, style: _textStyle),
);
}
return Text(keyName, style: _textStyle);
}
@override
void initState() {
super.initState();
if (widget.initialValue is bool) {
_value = widget.initialValue;
} else {
if (widget.initialValue == _newKey) {
_text = "";
_isFocused = true;
_focusNode.requestFocus();
} else {
_text = widget.initialValue.toString();
}
}
if (widget.isKey) {
_constraints = const BoxConstraints(minWidth: 20, maxWidth: 100);
} else if (widget.initialValue is num) {
_constraints = const BoxConstraints(minWidth: 20, maxWidth: 80);
} else {
_constraints = const BoxConstraints(minWidth: 20, maxWidth: 200);
}
_focusNode.addListener(handleChange);
}
@override
void dispose() {
_focusNode.removeListener(handleChange);
_focusNode.dispose();
super.dispose();
}