-
Notifications
You must be signed in to change notification settings - Fork 26.8k
/
reorderable_list.dart
1433 lines (1299 loc) · 47.6 KB
/
reorderable_list.dart
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
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';
import 'basic.dart';
import 'debug.dart';
import 'framework.dart';
import 'inherited_theme.dart';
import 'media_query.dart';
import 'overlay.dart';
import 'scroll_controller.dart';
import 'scroll_delegate.dart';
import 'scroll_physics.dart';
import 'scroll_view.dart';
import 'scrollable.dart';
import 'scrollable_helpers.dart';
import 'sliver.dart';
import 'sliver_prototype_extent_list.dart';
import 'ticker_provider.dart';
import 'transitions.dart';
// Examples can assume:
// class MyDataObject {}
/// A callback used by [ReorderableList] to report that a list item has moved
/// to a new position in the list.
///
/// Implementations should remove the corresponding list item at [oldIndex]
/// and reinsert it at [newIndex].
///
/// If [oldIndex] is before [newIndex], removing the item at [oldIndex] from the
/// list will reduce the list's length by one. Implementations will need to
/// account for this when inserting before [newIndex].
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=3fB1mxOsqJE}
///
/// {@tool snippet}
///
/// ```dart
/// final List<MyDataObject> backingList = <MyDataObject>[/* ... */];
///
/// void handleReorder(int oldIndex, int newIndex) {
/// if (oldIndex < newIndex) {
/// // removing the item at oldIndex will shorten the list by 1.
/// newIndex -= 1;
/// }
/// final MyDataObject element = backingList.removeAt(oldIndex);
/// backingList.insert(newIndex, element);
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [ReorderableList], a widget list that allows the user to reorder
/// its items.
/// * [SliverReorderableList], a sliver list that allows the user to reorder
/// its items.
/// * [ReorderableListView], a Material Design list that allows the user to
/// reorder its items.
typedef ReorderCallback = void Function(int oldIndex, int newIndex);
/// Signature for the builder callback used to decorate the dragging item in
/// [ReorderableList] and [SliverReorderableList].
///
/// The [child] will be the item that is being dragged, and [index] is the
/// position of the item in the list.
///
/// The [animation] will be driven forward from 0.0 to 1.0 while the item is
/// being picked up during a drag operation, and reversed from 1.0 to 0.0 when
/// the item is dropped. This can be used to animate properties of the proxy
/// like an elevation or border.
///
/// The returned value will typically be the [child] wrapped in other widgets.
typedef ReorderItemProxyDecorator = Widget Function(Widget child, int index, Animation<double> animation);
/// A scrolling container that allows the user to interactively reorder the
/// list items.
///
/// This widget is similar to one created by [ListView.builder], and uses
/// an [IndexedWidgetBuilder] to create each item.
///
/// It is up to the application to wrap each child (or an internal part of the
/// child such as a drag handle) with a drag listener that will recognize
/// the start of an item drag and then start the reorder by calling
/// [ReorderableListState.startItemDragReorder]. This is most easily achieved
/// by wrapping each child in a [ReorderableDragStartListener] or a
/// [ReorderableDelayedDragStartListener]. These will take care of recognizing
/// the start of a drag gesture and call the list state's
/// [ReorderableListState.startItemDragReorder] method.
///
/// This widget's [ReorderableListState] can be used to manually start an item
/// reorder, or cancel a current drag. To refer to the
/// [ReorderableListState] either provide a [GlobalKey] or use the static
/// [ReorderableList.of] method from an item's build method.
///
/// See also:
///
/// * [SliverReorderableList], a sliver list that allows the user to reorder
/// its items.
/// * [ReorderableListView], a Material Design list that allows the user to
/// reorder its items.
class ReorderableList extends StatefulWidget {
/// Creates a scrolling container that allows the user to interactively
/// reorder the list items.
///
/// The [itemCount] must be greater than or equal to zero.
const ReorderableList({
super.key,
required this.itemBuilder,
required this.itemCount,
required this.onReorder,
this.onReorderStart,
this.onReorderEnd,
this.itemExtent,
this.prototypeItem,
this.proxyDecorator,
this.padding,
this.scrollDirection = Axis.vertical,
this.reverse = false,
this.controller,
this.primary,
this.physics,
this.shrinkWrap = false,
this.anchor = 0.0,
this.cacheExtent,
this.dragStartBehavior = DragStartBehavior.start,
this.keyboardDismissBehavior = ScrollViewKeyboardDismissBehavior.manual,
this.restorationId,
this.clipBehavior = Clip.hardEdge,
}) : assert(itemCount >= 0),
assert(
itemExtent == null || prototypeItem == null,
'You can only pass itemExtent or prototypeItem, not both',
);
/// {@template flutter.widgets.reorderable_list.itemBuilder}
/// Called, as needed, to build list item widgets.
///
/// List items are only built when they're scrolled into view.
///
/// The [IndexedWidgetBuilder] index parameter indicates the item's
/// position in the list. The value of the index parameter will be between
/// zero and one less than [itemCount]. All items in the list must have a
/// unique [Key], and should have some kind of listener to start the drag
/// (usually a [ReorderableDragStartListener] or
/// [ReorderableDelayedDragStartListener]).
/// {@endtemplate}
final IndexedWidgetBuilder itemBuilder;
/// {@template flutter.widgets.reorderable_list.itemCount}
/// The number of items in the list.
///
/// It must be a non-negative integer. When zero, nothing is displayed and
/// the widget occupies no space.
/// {@endtemplate}
final int itemCount;
/// {@template flutter.widgets.reorderable_list.onReorder}
/// A callback used by the list to report that a list item has been dragged
/// to a new location in the list and the application should update the order
/// of the items.
/// {@endtemplate}
final ReorderCallback onReorder;
/// {@template flutter.widgets.reorderable_list.onReorderStart}
/// A callback that is called when an item drag has started.
///
/// The index parameter of the callback is the index of the selected item.
///
/// See also:
///
/// * [onReorderEnd], which is a called when the dragged item is dropped.
/// * [onReorder], which reports that a list item has been dragged to a new
/// location.
/// {@endtemplate}
final void Function(int index)? onReorderStart;
/// {@template flutter.widgets.reorderable_list.onReorderEnd}
/// A callback that is called when the dragged item is dropped.
///
/// The index parameter of the callback is the index where the item is
/// dropped. Unlike [onReorder], this is called even when the list item is
/// dropped in the same location.
///
/// See also:
///
/// * [onReorderStart], which is a called when an item drag has started.
/// * [onReorder], which reports that a list item has been dragged to a new
/// location.
/// {@endtemplate}
final void Function(int index)? onReorderEnd;
/// {@template flutter.widgets.reorderable_list.proxyDecorator}
/// A callback that allows the app to add an animated decoration around
/// an item when it is being dragged.
/// {@endtemplate}
final ReorderItemProxyDecorator? proxyDecorator;
/// {@template flutter.widgets.reorderable_list.padding}
/// The amount of space by which to inset the list contents.
///
/// It defaults to `EdgeInsets.all(0)`.
/// {@endtemplate}
final EdgeInsetsGeometry? padding;
/// {@macro flutter.widgets.scroll_view.scrollDirection}
final Axis scrollDirection;
/// {@macro flutter.widgets.scroll_view.reverse}
final bool reverse;
/// {@macro flutter.widgets.scroll_view.controller}
final ScrollController? controller;
/// {@macro flutter.widgets.scroll_view.primary}
final bool? primary;
/// {@macro flutter.widgets.scroll_view.physics}
final ScrollPhysics? physics;
/// {@macro flutter.widgets.scroll_view.shrinkWrap}
final bool shrinkWrap;
/// {@macro flutter.widgets.scroll_view.anchor}
final double anchor;
/// {@macro flutter.rendering.RenderViewportBase.cacheExtent}
final double? cacheExtent;
/// {@macro flutter.widgets.scrollable.dragStartBehavior}
final DragStartBehavior dragStartBehavior;
/// {@macro flutter.widgets.scroll_view.keyboardDismissBehavior}
///
/// The default is [ScrollViewKeyboardDismissBehavior.manual]
final ScrollViewKeyboardDismissBehavior keyboardDismissBehavior;
/// {@macro flutter.widgets.scrollable.restorationId}
final String? restorationId;
/// {@macro flutter.material.Material.clipBehavior}
///
/// Defaults to [Clip.hardEdge].
final Clip clipBehavior;
/// {@macro flutter.widgets.list_view.itemExtent}
final double? itemExtent;
/// {@macro flutter.widgets.list_view.prototypeItem}
final Widget? prototypeItem;
/// The state from the closest instance of this class that encloses the given
/// context.
///
/// This method is typically used by [ReorderableList] item widgets that
/// insert or remove items in response to user input.
///
/// If no [ReorderableList] surrounds the given context, then this function
/// will assert in debug mode and throw an exception in release mode.
///
/// This method can be expensive (it walks the element tree).
///
/// See also:
///
/// * [maybeOf], a similar function that will return null if no
/// [ReorderableList] ancestor is found.
static ReorderableListState of(BuildContext context) {
final ReorderableListState? result = context.findAncestorStateOfType<ReorderableListState>();
assert(() {
if (result == null) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('ReorderableList.of() called with a context that does not contain a ReorderableList.'),
ErrorDescription(
'No ReorderableList ancestor could be found starting from the context that was passed to ReorderableList.of().',
),
ErrorHint(
'This can happen when the context provided is from the same StatefulWidget that '
'built the ReorderableList. Please see the ReorderableList documentation for examples '
'of how to refer to an ReorderableListState object:\n'
' https://api.flutter.dev/flutter/widgets/ReorderableListState-class.html',
),
context.describeElement('The context used was'),
]);
}
return true;
}());
return result!;
}
/// The state from the closest instance of this class that encloses the given
/// context.
///
/// This method is typically used by [ReorderableList] item widgets that insert
/// or remove items in response to user input.
///
/// If no [ReorderableList] surrounds the context given, then this function will
/// return null.
///
/// This method can be expensive (it walks the element tree).
///
/// See also:
///
/// * [of], a similar function that will throw if no [ReorderableList] ancestor
/// is found.
static ReorderableListState? maybeOf(BuildContext context) {
return context.findAncestorStateOfType<ReorderableListState>();
}
@override
ReorderableListState createState() => ReorderableListState();
}
/// The state for a list that allows the user to interactively reorder
/// the list items.
///
/// An app that needs to start a new item drag or cancel an existing one
/// can refer to the [ReorderableList]'s state with a global key:
///
/// ```dart
/// GlobalKey<ReorderableListState> listKey = GlobalKey<ReorderableListState>();
/// // ...
/// Widget build(BuildContext context) {
/// return ReorderableList(
/// key: listKey,
/// itemBuilder: (BuildContext context, int index) => const SizedBox(height: 10.0),
/// itemCount: 5,
/// onReorder: (int oldIndex, int newIndex) {
/// // ...
/// },
/// );
/// }
/// // ...
/// listKey.currentState!.cancelReorder();
/// ```
class ReorderableListState extends State<ReorderableList> {
final GlobalKey<SliverReorderableListState> _sliverReorderableListKey = GlobalKey();
/// Initiate the dragging of the item at [index] that was started with
/// the pointer down [event].
///
/// The given [recognizer] will be used to recognize and start the drag
/// item tracking and lead to either an item reorder, or a canceled drag.
/// The list will take ownership of the returned recognizer and will dispose
/// it when it is no longer needed.
///
/// Most applications will not use this directly, but will wrap the item
/// (or part of the item, like a drag handle) in either a
/// [ReorderableDragStartListener] or [ReorderableDelayedDragStartListener]
/// which call this for the application.
void startItemDragReorder({
required int index,
required PointerDownEvent event,
required MultiDragGestureRecognizer recognizer,
}) {
_sliverReorderableListKey.currentState!.startItemDragReorder(index: index, event: event, recognizer: recognizer);
}
/// Cancel any item drag in progress.
///
/// This should be called before any major changes to the item list
/// occur so that any item drags will not get confused by
/// changes to the underlying list.
///
/// If no drag is active, this will do nothing.
void cancelReorder() {
_sliverReorderableListKey.currentState!.cancelReorder();
}
@override
Widget build(BuildContext context) {
return CustomScrollView(
scrollDirection: widget.scrollDirection,
reverse: widget.reverse,
controller: widget.controller,
primary: widget.primary,
physics: widget.physics,
shrinkWrap: widget.shrinkWrap,
anchor: widget.anchor,
cacheExtent: widget.cacheExtent,
dragStartBehavior: widget.dragStartBehavior,
keyboardDismissBehavior: widget.keyboardDismissBehavior,
restorationId: widget.restorationId,
clipBehavior: widget.clipBehavior,
slivers: <Widget>[
SliverPadding(
padding: widget.padding ?? EdgeInsets.zero,
sliver: SliverReorderableList(
key: _sliverReorderableListKey,
itemExtent: widget.itemExtent,
prototypeItem: widget.prototypeItem,
itemBuilder: widget.itemBuilder,
itemCount: widget.itemCount,
onReorder: widget.onReorder,
onReorderStart: widget.onReorderStart,
onReorderEnd: widget.onReorderEnd,
proxyDecorator: widget.proxyDecorator,
),
),
],
);
}
}
/// A sliver list that allows the user to interactively reorder the list items.
///
/// It is up to the application to wrap each child (or an internal part of the
/// child) with a drag listener that will recognize the start of an item drag
/// and then start the reorder by calling
/// [SliverReorderableListState.startItemDragReorder]. This is most easily
/// achieved by wrapping each child in a [ReorderableDragStartListener] or
/// a [ReorderableDelayedDragStartListener]. These will take care of
/// recognizing the start of a drag gesture and call the list state's start
/// item drag method.
///
/// This widget's [SliverReorderableListState] can be used to manually start an item
/// reorder, or cancel a current drag that's already underway. To refer to the
/// [SliverReorderableListState] either provide a [GlobalKey] or use the static
/// [SliverReorderableList.of] method from an item's build method.
///
/// See also:
///
/// * [ReorderableList], a regular widget list that allows the user to reorder
/// its items.
/// * [ReorderableListView], a Material Design list that allows the user to
/// reorder its items.
class SliverReorderableList extends StatefulWidget {
/// Creates a sliver list that allows the user to interactively reorder its
/// items.
///
/// The [itemCount] must be greater than or equal to zero.
const SliverReorderableList({
super.key,
required this.itemBuilder,
this.findChildIndexCallback,
required this.itemCount,
required this.onReorder,
this.onReorderStart,
this.onReorderEnd,
this.itemExtent,
this.prototypeItem,
this.proxyDecorator,
}) : assert(itemCount >= 0),
assert(
itemExtent == null || prototypeItem == null,
'You can only pass itemExtent or prototypeItem, not both',
);
/// {@macro flutter.widgets.reorderable_list.itemBuilder}
final IndexedWidgetBuilder itemBuilder;
/// {@macro flutter.widgets.SliverChildBuilderDelegate.findChildIndexCallback}
final ChildIndexGetter? findChildIndexCallback;
/// {@macro flutter.widgets.reorderable_list.itemCount}
final int itemCount;
/// {@macro flutter.widgets.reorderable_list.onReorder}
final ReorderCallback onReorder;
/// {@macro flutter.widgets.reorderable_list.onReorderStart}
final void Function(int)? onReorderStart;
/// {@macro flutter.widgets.reorderable_list.onReorderEnd}
final void Function(int)? onReorderEnd;
/// {@macro flutter.widgets.reorderable_list.proxyDecorator}
final ReorderItemProxyDecorator? proxyDecorator;
/// {@macro flutter.widgets.list_view.itemExtent}
final double? itemExtent;
/// {@macro flutter.widgets.list_view.prototypeItem}
final Widget? prototypeItem;
@override
SliverReorderableListState createState() => SliverReorderableListState();
/// The state from the closest instance of this class that encloses the given
/// context.
///
/// This method is typically used by [SliverReorderableList] item widgets to
/// start or cancel an item drag operation.
///
/// If no [SliverReorderableList] surrounds the context given, this function
/// will assert in debug mode and throw an exception in release mode.
///
/// This method can be expensive (it walks the element tree).
///
/// See also:
///
/// * [maybeOf], a similar function that will return null if no
/// [SliverReorderableList] ancestor is found.
static SliverReorderableListState of(BuildContext context) {
final SliverReorderableListState? result = context.findAncestorStateOfType<SliverReorderableListState>();
assert(() {
if (result == null) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary(
'SliverReorderableList.of() called with a context that does not contain a SliverReorderableList.',
),
ErrorDescription(
'No SliverReorderableList ancestor could be found starting from the context that was passed to SliverReorderableList.of().',
),
ErrorHint(
'This can happen when the context provided is from the same StatefulWidget that '
'built the SliverReorderableList. Please see the SliverReorderableList documentation for examples '
'of how to refer to an SliverReorderableList object:\n'
' https://api.flutter.dev/flutter/widgets/SliverReorderableListState-class.html',
),
context.describeElement('The context used was'),
]);
}
return true;
}());
return result!;
}
/// The state from the closest instance of this class that encloses the given
/// context.
///
/// This method is typically used by [SliverReorderableList] item widgets that
/// insert or remove items in response to user input.
///
/// If no [SliverReorderableList] surrounds the context given, this function
/// will return null.
///
/// This method can be expensive (it walks the element tree).
///
/// See also:
///
/// * [of], a similar function that will throw if no [SliverReorderableList]
/// ancestor is found.
static SliverReorderableListState? maybeOf(BuildContext context) {
return context.findAncestorStateOfType<SliverReorderableListState>();
}
}
/// The state for a sliver list that allows the user to interactively reorder
/// the list items.
///
/// An app that needs to start a new item drag or cancel an existing one
/// can refer to the [SliverReorderableList]'s state with a global key:
///
/// ```dart
/// // (e.g. in a stateful widget)
/// GlobalKey<SliverReorderableListState> listKey = GlobalKey<SliverReorderableListState>();
///
/// // ...
///
/// @override
/// Widget build(BuildContext context) {
/// return SliverReorderableList(
/// key: listKey,
/// itemBuilder: (BuildContext context, int index) => const SizedBox(height: 10.0),
/// itemCount: 5,
/// onReorder: (int oldIndex, int newIndex) {
/// // ...
/// },
/// );
/// }
///
/// // ...
///
/// void _stop() {
/// listKey.currentState!.cancelReorder();
/// }
/// ```
///
/// [ReorderableDragStartListener] and [ReorderableDelayedDragStartListener]
/// refer to their [SliverReorderableList] with the static
/// [SliverReorderableList.of] method.
class SliverReorderableListState extends State<SliverReorderableList> with TickerProviderStateMixin {
// Map of index -> child state used manage where the dragging item will need
// to be inserted.
final Map<int, _ReorderableItemState> _items = <int, _ReorderableItemState>{};
OverlayEntry? _overlayEntry;
int? _dragIndex;
_DragInfo? _dragInfo;
int? _insertIndex;
Offset? _finalDropPosition;
MultiDragGestureRecognizer? _recognizer;
int? _recognizerPointer;
// To implement the gap for the dragged item, we replace the dragged item
// with a zero sized box, and then translate all of the later items down
// by the size of the dragged item. This allows us to keep the order of the
// list, while still being able to animate the gap between the items. However
// for the first frame of the drag, the item has not yet been replaced, so
// the calculation for the gap is off by the size of the gap. This flag is
// used to determine if the transition to the zero sized box has completed,
// so the gap calculation can compensate for it.
bool _dragStartTransitionComplete = false;
EdgeDraggingAutoScroller? _autoScroller;
late ScrollableState _scrollable;
Axis get _scrollDirection => axisDirectionToAxis(_scrollable.axisDirection);
bool get _reverse =>
_scrollable.axisDirection == AxisDirection.up ||
_scrollable.axisDirection == AxisDirection.left;
@override
void didChangeDependencies() {
super.didChangeDependencies();
_scrollable = Scrollable.of(context);
if (_autoScroller?.scrollable != _scrollable) {
_autoScroller?.stopAutoScroll();
_autoScroller = EdgeDraggingAutoScroller(
_scrollable,
onScrollViewScrolled: _handleScrollableAutoScrolled
);
}
}
@override
void didUpdateWidget(covariant SliverReorderableList oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.itemCount != oldWidget.itemCount) {
cancelReorder();
}
}
@override
void dispose() {
_dragReset();
super.dispose();
}
/// Initiate the dragging of the item at [index] that was started with
/// the pointer down [event].
///
/// The given [recognizer] will be used to recognize and start the drag
/// item tracking and lead to either an item reorder, or a canceled drag.
///
/// Most applications will not use this directly, but will wrap the item
/// (or part of the item, like a drag handle) in either a
/// [ReorderableDragStartListener] or [ReorderableDelayedDragStartListener]
/// which call this method when they detect the gesture that triggers a drag
/// start.
void startItemDragReorder({
required int index,
required PointerDownEvent event,
required MultiDragGestureRecognizer recognizer,
}) {
assert(0 <= index && index < widget.itemCount);
setState(() {
if (_dragInfo != null) {
cancelReorder();
} else if (_recognizer != null && _recognizerPointer != event.pointer) {
_recognizer!.dispose();
_recognizer = null;
_recognizerPointer = null;
}
if (_items.containsKey(index)) {
_dragIndex = index;
_recognizer = recognizer
..onStart = _dragStart
..addPointer(event);
_recognizerPointer = event.pointer;
} else {
// TODO(darrenaustin): Can we handle this better, maybe scroll to the item?
throw Exception('Attempting to start a drag on a non-visible item');
}
});
}
/// Cancel any item drag in progress.
///
/// This should be called before any major changes to the item list
/// occur so that any item drags will not get confused by
/// changes to the underlying list.
///
/// If a drag operation is in progress, this will immediately reset
/// the list to back to its pre-drag state.
///
/// If no drag is active, this will do nothing.
void cancelReorder() {
setState(() {
_dragReset();
});
}
void _registerItem(_ReorderableItemState item) {
_items[item.index] = item;
if (item.index == _dragInfo?.index) {
item.dragging = true;
item.rebuild();
}
}
void _unregisterItem(int index, _ReorderableItemState item) {
final _ReorderableItemState? currentItem = _items[index];
if (currentItem == item) {
_items.remove(index);
}
}
Drag? _dragStart(Offset position) {
assert(_dragInfo == null);
final _ReorderableItemState item = _items[_dragIndex!]!;
item.dragging = true;
widget.onReorderStart?.call(_dragIndex!);
item.rebuild();
_dragStartTransitionComplete = false;
SchedulerBinding.instance.addPostFrameCallback((Duration duration) {
_dragStartTransitionComplete = true;
});
_insertIndex = item.index;
_dragInfo = _DragInfo(
item: item,
initialPosition: position,
scrollDirection: _scrollDirection,
onUpdate: _dragUpdate,
onCancel: _dragCancel,
onEnd: _dragEnd,
onDropCompleted: _dropCompleted,
proxyDecorator: widget.proxyDecorator,
tickerProvider: this,
);
_dragInfo!.startDrag();
final OverlayState overlay = Overlay.of(context, debugRequiredFor: widget);
assert(_overlayEntry == null);
_overlayEntry = OverlayEntry(builder: _dragInfo!.createProxy);
overlay.insert(_overlayEntry!);
for (final _ReorderableItemState childItem in _items.values) {
if (childItem == item || !childItem.mounted) {
continue;
}
childItem.updateForGap(_insertIndex!, _dragInfo!.itemExtent, false, _reverse);
}
return _dragInfo;
}
void _dragUpdate(_DragInfo item, Offset position, Offset delta) {
setState(() {
_overlayEntry?.markNeedsBuild();
_dragUpdateItems();
_autoScroller?.startAutoScrollIfNecessary(_dragTargetRect);
});
}
void _dragCancel(_DragInfo item) {
setState(() {
_dragReset();
});
}
void _dragEnd(_DragInfo item) {
setState(() {
if (_insertIndex == item.index) {
_finalDropPosition = _itemOffsetAt(_insertIndex! + (_reverse ? 1 : 0));
} else if (_insertIndex! < widget.itemCount - 1) {
// Find the location of the item we want to insert before
_finalDropPosition = _itemOffsetAt(_insertIndex!);
} else {
// Inserting into the last spot on the list. If it's the only spot, put
// it back where it was. Otherwise, grab the second to last and move
// down by the gap.
final int itemIndex = _items.length > 1 ? _insertIndex! - 1 : _insertIndex!;
if (_reverse) {
_finalDropPosition = _itemOffsetAt(itemIndex) - _extentOffset(item.itemExtent, _scrollDirection);
} else {
_finalDropPosition = _itemOffsetAt(itemIndex) + _extentOffset(item.itemExtent, _scrollDirection);
}
}
});
widget.onReorderEnd?.call(_insertIndex!);
}
void _dropCompleted() {
final int fromIndex = _dragIndex!;
final int toIndex = _insertIndex!;
if (fromIndex != toIndex) {
widget.onReorder.call(fromIndex, toIndex);
}
setState(() {
_dragReset();
});
}
void _dragReset() {
if (_dragInfo != null) {
if (_dragIndex != null && _items.containsKey(_dragIndex)) {
final _ReorderableItemState dragItem = _items[_dragIndex!]!;
dragItem._dragging = false;
dragItem.rebuild();
_dragIndex = null;
}
_dragInfo?.dispose();
_dragInfo = null;
_autoScroller?.stopAutoScroll();
_resetItemGap();
_recognizer?.dispose();
_recognizer = null;
_overlayEntry?.remove();
_overlayEntry = null;
_finalDropPosition = null;
}
}
void _resetItemGap() {
for (final _ReorderableItemState item in _items.values) {
item.resetGap();
}
}
void _handleScrollableAutoScrolled() {
if (_dragInfo == null) {
return;
}
_dragUpdateItems();
// Continue scrolling if the drag is still in progress.
_autoScroller?.startAutoScrollIfNecessary(_dragTargetRect);
}
void _dragUpdateItems() {
assert(_dragInfo != null);
final double gapExtent = _dragInfo!.itemExtent;
final double proxyItemStart = _offsetExtent(_dragInfo!.dragPosition - _dragInfo!.dragOffset, _scrollDirection);
final double proxyItemEnd = proxyItemStart + gapExtent;
// Find the new index for inserting the item being dragged.
int newIndex = _insertIndex!;
for (final _ReorderableItemState item in _items.values) {
if (item.index == _dragIndex! || !item.mounted) {
continue;
}
Rect geometry = item.targetGeometry();
if (!_dragStartTransitionComplete && _dragIndex! <= item.index) {
// Transition is not complete, so each item after the dragged item is still
// in its normal location and not moved up for the zero sized box that will
// replace the dragged item.
final Offset transitionOffset = _extentOffset(_reverse ? -gapExtent : gapExtent, _scrollDirection);
geometry = (geometry.topLeft - transitionOffset) & geometry.size;
}
final double itemStart = _scrollDirection == Axis.vertical ? geometry.top : geometry.left;
final double itemExtent = _scrollDirection == Axis.vertical ? geometry.height : geometry.width;
final double itemEnd = itemStart + itemExtent;
final double itemMiddle = itemStart + itemExtent / 2;
if (_reverse) {
if (itemEnd >= proxyItemEnd && proxyItemEnd >= itemMiddle) {
// The start of the proxy is in the beginning half of the item, so
// we should swap the item with the gap and we are done looking for
// the new index.
newIndex = item.index;
break;
} else if (itemMiddle >= proxyItemStart && proxyItemStart >= itemStart) {
// The end of the proxy is in the ending half of the item, so
// we should swap the item with the gap and we are done looking for
// the new index.
newIndex = item.index + 1;
break;
} else if (itemStart > proxyItemEnd && newIndex < (item.index + 1)) {
newIndex = item.index + 1;
} else if (proxyItemStart > itemEnd && newIndex > item.index) {
newIndex = item.index;
}
} else {
if (itemStart <= proxyItemStart && proxyItemStart <= itemMiddle) {
// The start of the proxy is in the beginning half of the item, so
// we should swap the item with the gap and we are done looking for
// the new index.
newIndex = item.index;
break;
} else if (itemMiddle <= proxyItemEnd && proxyItemEnd <= itemEnd) {
// The end of the proxy is in the ending half of the item, so
// we should swap the item with the gap and we are done looking for
// the new index.
newIndex = item.index + 1;
break;
} else if (itemEnd < proxyItemStart && newIndex < (item.index + 1)) {
newIndex = item.index + 1;
} else if (proxyItemEnd < itemStart && newIndex > item.index) {
newIndex = item.index;
}
}
}
if (newIndex != _insertIndex) {
_insertIndex = newIndex;
for (final _ReorderableItemState item in _items.values) {
if (item.index == _dragIndex! || !item.mounted) {
continue;
}
item.updateForGap(newIndex, gapExtent, true, _reverse);
}
}
}
Rect get _dragTargetRect {
final Offset origin = _dragInfo!.dragPosition - _dragInfo!.dragOffset;
return Rect.fromLTWH(origin.dx, origin.dy, _dragInfo!.itemSize.width, _dragInfo!.itemSize.height);
}
Offset _itemOffsetAt(int index) {
final RenderBox itemRenderBox = _items[index]!.context.findRenderObject()! as RenderBox;
return itemRenderBox.localToGlobal(Offset.zero);
}
Widget _itemBuilder(BuildContext context, int index) {
if (_dragInfo != null && index >= widget.itemCount) {
switch (_scrollDirection) {
case Axis.horizontal:
return SizedBox(width: _dragInfo!.itemExtent);
case Axis.vertical:
return SizedBox(height: _dragInfo!.itemExtent);
}
}
final Widget child = widget.itemBuilder(context, index);
assert(child.key != null, 'All list items must have a key');
final OverlayState overlay = Overlay.of(context, debugRequiredFor: widget);
return _ReorderableItem(
key: _ReorderableItemGlobalKey(child.key!, index, this),
index: index,
capturedThemes: InheritedTheme.capture(from: context, to: overlay.context),
child: child,
);
}
@override
Widget build(BuildContext context) {
assert(debugCheckHasOverlay(context));
final SliverChildBuilderDelegate childrenDelegate = SliverChildBuilderDelegate(
_itemBuilder,
// When dragging, the dragged item is still in the list but has been replaced
// by a zero height SizedBox, so that the gap can move around. To make the
// list extent stable we add a dummy entry to the end.
childCount: widget.itemCount + (_dragInfo != null ? 1 : 0),
findChildIndexCallback: widget.findChildIndexCallback,
);
if (widget.itemExtent != null) {
return SliverFixedExtentList(
delegate: childrenDelegate,
itemExtent: widget.itemExtent!,
);
} else if (widget.prototypeItem != null) {
return SliverPrototypeExtentList(
delegate: childrenDelegate,
prototypeItem: widget.prototypeItem!,
);
}
return SliverList(delegate: childrenDelegate);
}
}
class _ReorderableItem extends StatefulWidget {
const _ReorderableItem({
required Key key,
required this.index,
required this.child,
required this.capturedThemes,
}) : super(key: key);
final int index;
final Widget child;
final CapturedThemes capturedThemes;
@override
_ReorderableItemState createState() => _ReorderableItemState();
}
class _ReorderableItemState extends State<_ReorderableItem> {
late SliverReorderableListState _listState;
Offset _startOffset = Offset.zero;
Offset _targetOffset = Offset.zero;
AnimationController? _offsetAnimation;
Key get key => widget.key!;
int get index => widget.index;
bool get dragging => _dragging;
set dragging(bool dragging) {
if (mounted) {
setState(() {
_dragging = dragging;
});
}
}
bool _dragging = false;
@override
void initState() {
_listState = SliverReorderableList.of(context);
_listState._registerItem(this);