New Reorderable list widgets (#74299)
Introduced new widget/ReorderableList and widget/SliverReorderableList widgets.
This commit is contained in:
@@ -51,7 +51,6 @@ bool debugCheckHasMaterial(BuildContext context) {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/// Asserts that the given context has a [Localizations] ancestor that contains
|
||||
/// a [MaterialLocalizations] delegate.
|
||||
///
|
||||
|
||||
@@ -2,47 +2,16 @@
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'dart:math';
|
||||
import 'dart:ui' show lerpDouble;
|
||||
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter/rendering.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import 'debug.dart';
|
||||
import 'icons.dart';
|
||||
import 'material.dart';
|
||||
import 'material_localizations.dart';
|
||||
|
||||
// Examples can assume:
|
||||
// class MyDataObject { }
|
||||
|
||||
/// The callback used by [ReorderableListView] to move an item to a new
|
||||
/// position in a 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 used by
|
||||
/// [ReorderableListView] 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}
|
||||
typedef ReorderCallback = void Function(int oldIndex, int newIndex);
|
||||
import 'theme.dart';
|
||||
|
||||
/// A list whose items the user can interactively reorder by dragging.
|
||||
///
|
||||
@@ -62,25 +31,30 @@ typedef ReorderCallback = void Function(int oldIndex, int newIndex);
|
||||
/// {@tool dartpad --template=stateful_widget_scaffold}
|
||||
///
|
||||
/// ```dart
|
||||
/// List<String> _list = List.generate(5, (i) => "${i}");
|
||||
/// final List<int> _items = List<int>.generate(50, (int index) => index);
|
||||
///
|
||||
/// Widget build(BuildContext context){
|
||||
/// final ColorScheme colorScheme = Theme.of(context).colorScheme;
|
||||
/// final oddItemColor = colorScheme.primary.withOpacity(0.05);
|
||||
/// final evenItemColor = colorScheme.primary.withOpacity(0.15);
|
||||
///
|
||||
/// return ReorderableListView(
|
||||
/// padding : const EdgeInsets.symmetric(horizontal:40),
|
||||
/// children:[
|
||||
/// for(var i=0 ; i<_list.length ; i++)
|
||||
/// padding: const EdgeInsets.symmetric(horizontal: 40),
|
||||
/// children: <Widget>[
|
||||
/// for (int index = 0; index < _items.length; index++)
|
||||
/// ListTile(
|
||||
/// key:Key('$i'),
|
||||
/// title: Text(_list[i]),
|
||||
/// key: Key('$index'),
|
||||
/// tileColor: _items[index].isOdd ? oddItemColor : evenItemColor,
|
||||
/// title: Text('Item ${_items[index]}'),
|
||||
/// ),
|
||||
/// ],
|
||||
/// onReorder: (oldIndex, newIndex){
|
||||
/// setState((){
|
||||
/// if(oldIndex < newIndex){
|
||||
/// newIndex-=1;
|
||||
/// onReorder: (int oldIndex, int newIndex) {
|
||||
/// setState(() {
|
||||
/// if (oldIndex < newIndex) {
|
||||
/// newIndex -= 1;
|
||||
/// }
|
||||
/// final element = _list.removeAt(oldIndex);
|
||||
/// _list.insert(newIndex, element);
|
||||
/// final int item = _items.removeAt(oldIndex);
|
||||
/// _items.insert(newIndex, item);
|
||||
/// });
|
||||
/// },
|
||||
/// );
|
||||
@@ -89,9 +63,7 @@ typedef ReorderCallback = void Function(int oldIndex, int newIndex);
|
||||
/// ```
|
||||
///
|
||||
///{@end-tool}
|
||||
///
|
||||
class ReorderableListView extends StatefulWidget {
|
||||
|
||||
/// Creates a reorderable list.
|
||||
ReorderableListView({
|
||||
Key? key,
|
||||
@@ -102,6 +74,8 @@ class ReorderableListView extends StatefulWidget {
|
||||
this.scrollDirection = Axis.vertical,
|
||||
this.padding,
|
||||
this.reverse = false,
|
||||
this.buildDefaultDragHandles = true,
|
||||
this.proxyDecorator,
|
||||
}) : assert(scrollDirection != null),
|
||||
assert(onReorder != null),
|
||||
assert(children != null),
|
||||
@@ -109,6 +83,7 @@ class ReorderableListView extends StatefulWidget {
|
||||
children.every((Widget w) => w.key != null),
|
||||
'All children of this widget must have a key.',
|
||||
),
|
||||
assert(buildDefaultDragHandles != null),
|
||||
super(key: key);
|
||||
|
||||
/// A non-reorderable header widget to show before the list.
|
||||
@@ -157,23 +132,94 @@ class ReorderableListView extends StatefulWidget {
|
||||
/// into a new position.
|
||||
final ReorderCallback onReorder;
|
||||
|
||||
/// If true: on desktop platforms, a drag handle is stacked over the
|
||||
/// center of each item's trailing edge; on mobile platforms, a long
|
||||
/// press anywhere on the item starts a drag.
|
||||
///
|
||||
/// The default desktop drag handle is just an [Icons.drag_handle]
|
||||
/// wrapped by a [ReorderableDragStartListener]. On mobile
|
||||
/// platforms, the entire item is wrapped with a
|
||||
/// [ReorderableDelayedDragStartListener].
|
||||
///
|
||||
/// To change the appearance or the layout of the drag handles, make
|
||||
/// this parameter false and wrap each list item, or a widget within
|
||||
/// each list item, with [ReorderableDragStartListener] or
|
||||
/// [ReorderableDelayedDragStartListener], or a custom subclass
|
||||
/// of [ReorderableDragStartListener].
|
||||
///
|
||||
/// The following sample specifies `buildDefaultDragHandles: false`, and
|
||||
/// uses a [Card] at the leading edge of each item for the item's drag handle.
|
||||
///
|
||||
/// {@tool dartpad --template=stateful_widget_scaffold}
|
||||
///
|
||||
/// ```dart
|
||||
/// final List<int> _items = List<int>.generate(50, (int index) => index);
|
||||
///
|
||||
/// Widget build(BuildContext context){
|
||||
/// final ColorScheme colorScheme = Theme.of(context).colorScheme;
|
||||
/// final oddItemColor = colorScheme.primary.withOpacity(0.05);
|
||||
/// final evenItemColor = colorScheme.primary.withOpacity(0.15);
|
||||
///
|
||||
/// return ReorderableListView(
|
||||
/// buildDefaultDragHandles: false,
|
||||
/// children: <Widget>[
|
||||
/// for (int index = 0; index < _items.length; index++)
|
||||
/// Container(
|
||||
/// key: Key('$index'),
|
||||
/// color: _items[index].isOdd ? oddItemColor : evenItemColor,
|
||||
/// child: Row(
|
||||
/// children: <Widget>[
|
||||
/// Container(
|
||||
/// width: 64,
|
||||
/// height: 64,
|
||||
/// padding: const EdgeInsets.all(8),
|
||||
/// child: ReorderableDragStartListener(
|
||||
/// index: index,
|
||||
/// child: Card(
|
||||
/// color: colorScheme.primary,
|
||||
/// elevation: 2,
|
||||
/// ),
|
||||
/// ),
|
||||
/// ),
|
||||
/// Text('Item ${_items[index]}'),
|
||||
/// ],
|
||||
/// ),
|
||||
/// ),
|
||||
/// ],
|
||||
/// onReorder: (oldIndex, newIndex) {
|
||||
/// setState(() {
|
||||
/// if (oldIndex < newIndex) {
|
||||
/// newIndex -= 1;
|
||||
/// }
|
||||
/// final int item = _items.removeAt(oldIndex);
|
||||
/// _items.insert(newIndex, item);
|
||||
/// });
|
||||
/// },
|
||||
/// );
|
||||
/// }
|
||||
/// ```
|
||||
///{@end-tool}
|
||||
final bool buildDefaultDragHandles;
|
||||
|
||||
/// A callback that allows the app to add an animated decoration around
|
||||
/// an item when it is being dragged.
|
||||
///
|
||||
/// If this is null, a default decoration of a Material widget with
|
||||
/// an animated elevation will be used.
|
||||
final ReorderItemProxyDecorator? proxyDecorator;
|
||||
|
||||
@override
|
||||
_ReorderableListViewState createState() => _ReorderableListViewState();
|
||||
}
|
||||
|
||||
// This top-level state manages an Overlay that contains the list and
|
||||
// also any Draggables it creates.
|
||||
//
|
||||
// _ReorderableListContent manages the list itself and reorder operations.
|
||||
// also any items being dragged on top fo the list.
|
||||
//
|
||||
// The Overlay doesn't properly keep state by building new overlay entries,
|
||||
// and so we cache a single OverlayEntry for use as the list layer.
|
||||
// That overlay entry then builds a _ReorderableListContent which may
|
||||
// insert Draggables into the Overlay above itself.
|
||||
// insert items being dragged into the Overlay above itself.
|
||||
class _ReorderableListViewState extends State<ReorderableListView> {
|
||||
// We use an inner overlay so that the dragging list item doesn't draw outside of the list itself.
|
||||
final GlobalKey _overlayKey = GlobalKey(debugLabel: '$ReorderableListView overlay key');
|
||||
|
||||
// This entry contains the scrolling list itself.
|
||||
late OverlayEntry _listOverlayEntry;
|
||||
|
||||
@@ -188,26 +234,35 @@ class _ReorderableListViewState extends State<ReorderableListView> {
|
||||
children: widget.children,
|
||||
scrollController: widget.scrollController,
|
||||
scrollDirection: widget.scrollDirection,
|
||||
onReorder: widget.onReorder,
|
||||
padding: widget.padding,
|
||||
onReorder: widget.onReorder,
|
||||
reverse: widget.reverse,
|
||||
buildDefaultDragHandles: widget.buildDefaultDragHandles,
|
||||
proxyDecorator: widget.proxyDecorator,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(ReorderableListView oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
// As this depends on pretty much everything, it
|
||||
// is ok to mark this as dirty unconditionally.
|
||||
_listOverlayEntry.markNeedsBuild();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
assert(debugCheckHasMaterialLocalizations(context));
|
||||
return Overlay(
|
||||
key: _overlayKey,
|
||||
initialEntries: <OverlayEntry>[
|
||||
_listOverlayEntry,
|
||||
]);
|
||||
_listOverlayEntry
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// This widget is responsible for the inside of the Overlay in the
|
||||
// ReorderableListView.
|
||||
class _ReorderableListContent extends StatefulWidget {
|
||||
const _ReorderableListContent({
|
||||
required this.header,
|
||||
@@ -217,6 +272,8 @@ class _ReorderableListContent extends StatefulWidget {
|
||||
required this.padding,
|
||||
required this.onReorder,
|
||||
required this.reverse,
|
||||
required this.buildDefaultDragHandles,
|
||||
required this.proxyDecorator,
|
||||
});
|
||||
|
||||
final Widget? header;
|
||||
@@ -226,401 +283,188 @@ class _ReorderableListContent extends StatefulWidget {
|
||||
final EdgeInsets? padding;
|
||||
final ReorderCallback onReorder;
|
||||
final bool reverse;
|
||||
final bool buildDefaultDragHandles;
|
||||
final ReorderItemProxyDecorator? proxyDecorator;
|
||||
|
||||
@override
|
||||
_ReorderableListContentState createState() => _ReorderableListContentState();
|
||||
}
|
||||
|
||||
class _ReorderableListContentState extends State<_ReorderableListContent> with TickerProviderStateMixin<_ReorderableListContent> {
|
||||
|
||||
// The extent along the [widget.scrollDirection] axis to allow a child to
|
||||
// drop into when the user reorders list children.
|
||||
//
|
||||
// This value is used when the extents haven't yet been calculated from
|
||||
// the currently dragging widget, such as when it first builds.
|
||||
static const double _defaultDropAreaExtent = 100.0;
|
||||
|
||||
// How long an animation to reorder an element in the list takes.
|
||||
static const Duration _reorderAnimationDuration = Duration(milliseconds: 200);
|
||||
|
||||
// How long an animation to scroll to an off-screen element in the
|
||||
// list takes.
|
||||
static const Duration _scrollAnimationDuration = Duration(milliseconds: 200);
|
||||
|
||||
// Controls scrolls and measures scroll progress.
|
||||
late ScrollController _scrollController;
|
||||
|
||||
// This controls the entrance of the dragging widget into a new place.
|
||||
late AnimationController _entranceController;
|
||||
|
||||
// This controls the 'ghost' of the dragging widget, which is left behind
|
||||
// where the widget used to be.
|
||||
late AnimationController _ghostController;
|
||||
|
||||
// The member of widget.children currently being dragged.
|
||||
//
|
||||
// Null if no drag is underway.
|
||||
Key? _dragging;
|
||||
|
||||
// The last computed size of the feedback widget being dragged.
|
||||
Size? _draggingFeedbackSize;
|
||||
|
||||
// The location that the dragging widget occupied before it started to drag.
|
||||
int _dragStartIndex = 0;
|
||||
|
||||
// The index that the dragging widget most recently left.
|
||||
// This is used to show an animation of the widget's position.
|
||||
int _ghostIndex = 0;
|
||||
|
||||
// The index that the dragging widget currently occupies.
|
||||
int _currentIndex = 0;
|
||||
|
||||
// The widget to move the dragging widget too after the current index.
|
||||
int _nextIndex = 0;
|
||||
|
||||
// Whether or not we are currently scrolling this view to show a widget.
|
||||
bool _scrolling = false;
|
||||
|
||||
double get _dropAreaExtent {
|
||||
if (_draggingFeedbackSize == null) {
|
||||
return _defaultDropAreaExtent;
|
||||
}
|
||||
final double dropAreaWithoutMargin;
|
||||
switch (widget.scrollDirection) {
|
||||
case Axis.horizontal:
|
||||
dropAreaWithoutMargin = _draggingFeedbackSize!.width;
|
||||
break;
|
||||
case Axis.vertical:
|
||||
dropAreaWithoutMargin = _draggingFeedbackSize!.height;
|
||||
break;
|
||||
}
|
||||
return dropAreaWithoutMargin;
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_entranceController = AnimationController(vsync: this, duration: _reorderAnimationDuration);
|
||||
_ghostController = AnimationController(vsync: this, duration: _reorderAnimationDuration);
|
||||
_entranceController.addStatusListener(_onEntranceStatusChanged);
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeDependencies() {
|
||||
_scrollController = widget.scrollController ?? PrimaryScrollController.of(context) ?? ScrollController();
|
||||
super.didChangeDependencies();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_entranceController.dispose();
|
||||
_ghostController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
// Animates the droppable space from _currentIndex to _nextIndex.
|
||||
void _requestAnimationToNextIndex() {
|
||||
if (_entranceController.isCompleted) {
|
||||
_ghostIndex = _currentIndex;
|
||||
if (_nextIndex == _currentIndex) {
|
||||
return;
|
||||
}
|
||||
_currentIndex = _nextIndex;
|
||||
_ghostController.reverse(from: 1.0);
|
||||
_entranceController.forward(from: 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
// Requests animation to the latest next index if it changes during an animation.
|
||||
void _onEntranceStatusChanged(AnimationStatus status) {
|
||||
if (status == AnimationStatus.completed) {
|
||||
setState(() {
|
||||
_requestAnimationToNextIndex();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Scrolls to a target context if that context is not on the screen.
|
||||
void _scrollTo(BuildContext context) {
|
||||
if (_scrolling)
|
||||
return;
|
||||
final RenderObject contextObject = context.findRenderObject()!;
|
||||
final RenderAbstractViewport viewport = RenderAbstractViewport.of(contextObject)!;
|
||||
assert(viewport != null);
|
||||
// If and only if the current scroll offset falls in-between the offsets
|
||||
// necessary to reveal the selected context at the top or bottom of the
|
||||
// screen, then it is already on-screen.
|
||||
final double margin = _dropAreaExtent;
|
||||
final double scrollOffset = _scrollController.offset;
|
||||
final double topOffset = max(
|
||||
_scrollController.position.minScrollExtent,
|
||||
viewport.getOffsetToReveal(contextObject, 0.0).offset - margin,
|
||||
);
|
||||
final double bottomOffset = min(
|
||||
_scrollController.position.maxScrollExtent,
|
||||
viewport.getOffsetToReveal(contextObject, 1.0).offset + margin,
|
||||
);
|
||||
final bool onScreen = scrollOffset <= topOffset && scrollOffset >= bottomOffset;
|
||||
|
||||
// If the context is off screen, then we request a scroll to make it visible.
|
||||
if (!onScreen) {
|
||||
_scrolling = true;
|
||||
_scrollController.position.animateTo(
|
||||
scrollOffset < bottomOffset ? bottomOffset : topOffset,
|
||||
duration: _scrollAnimationDuration,
|
||||
curve: Curves.easeInOut,
|
||||
).then((void value) {
|
||||
setState(() {
|
||||
_scrolling = false;
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Wraps children in Row or Column, so that the children flow in
|
||||
// the widget's scrollDirection.
|
||||
Widget _buildContainerForScrollDirection({ required List<Widget> children }) {
|
||||
switch (widget.scrollDirection) {
|
||||
case Axis.horizontal:
|
||||
return Row(children: children);
|
||||
case Axis.vertical:
|
||||
return Column(children: children);
|
||||
}
|
||||
}
|
||||
|
||||
// Wraps one of the widget's children in a DragTarget and Draggable.
|
||||
// Handles up the logic for dragging and reordering items in the list.
|
||||
Widget _wrap(Widget toWrap, int index, BoxConstraints constraints) {
|
||||
assert(toWrap.key != null);
|
||||
final _ReorderableListViewChildGlobalKey keyIndexGlobalKey = _ReorderableListViewChildGlobalKey(toWrap.key!, this);
|
||||
// We pass the toWrapWithGlobalKey into the Draggable so that when a list
|
||||
// item gets dragged, the accessibility framework can preserve the selected
|
||||
// state of the dragging item.
|
||||
|
||||
// Starts dragging toWrap.
|
||||
void onDragStarted() {
|
||||
setState(() {
|
||||
_dragging = toWrap.key;
|
||||
_dragStartIndex = index;
|
||||
_ghostIndex = index;
|
||||
_currentIndex = index;
|
||||
_entranceController.value = 1.0;
|
||||
_draggingFeedbackSize = keyIndexGlobalKey.currentContext!.size;
|
||||
});
|
||||
}
|
||||
|
||||
// Places the value from startIndex one space before the element at endIndex.
|
||||
class _ReorderableListContentState extends State<_ReorderableListContent> {
|
||||
Widget _wrapWithSemantics(Widget child, int index) {
|
||||
void reorder(int startIndex, int endIndex) {
|
||||
setState(() {
|
||||
if (startIndex != endIndex)
|
||||
widget.onReorder(startIndex, endIndex);
|
||||
// Animates leftover space in the drop area closed.
|
||||
_ghostController.reverse(from: 0);
|
||||
_entranceController.reverse(from: 0);
|
||||
_dragging = null;
|
||||
});
|
||||
if (startIndex != endIndex)
|
||||
widget.onReorder(startIndex, endIndex);
|
||||
}
|
||||
|
||||
// Drops toWrap into the last position it was hovering over.
|
||||
void onDragEnded() {
|
||||
reorder(_dragStartIndex, _currentIndex);
|
||||
// First, determine which semantics actions apply.
|
||||
final Map<CustomSemanticsAction, VoidCallback> semanticsActions = <CustomSemanticsAction, VoidCallback>{};
|
||||
|
||||
// Create the appropriate semantics actions.
|
||||
void moveToStart() => reorder(index, 0);
|
||||
void moveToEnd() => reorder(index, widget.children.length);
|
||||
void moveBefore() => reorder(index, index - 1);
|
||||
// To move after, we go to index+2 because we are moving it to the space
|
||||
// before index+2, which is after the space at index+1.
|
||||
void moveAfter() => reorder(index, index + 2);
|
||||
|
||||
final MaterialLocalizations localizations = MaterialLocalizations.of(context);
|
||||
|
||||
// If the item can move to before its current position in the list.
|
||||
if (index > 0) {
|
||||
semanticsActions[CustomSemanticsAction(label: localizations.reorderItemToStart)] = moveToStart;
|
||||
String reorderItemBefore = localizations.reorderItemUp;
|
||||
if (widget.scrollDirection == Axis.horizontal) {
|
||||
reorderItemBefore = Directionality.of(context) == TextDirection.ltr
|
||||
? localizations.reorderItemLeft
|
||||
: localizations.reorderItemRight;
|
||||
}
|
||||
semanticsActions[CustomSemanticsAction(label: reorderItemBefore)] = moveBefore;
|
||||
}
|
||||
|
||||
Widget wrapWithSemantics() {
|
||||
// First, determine which semantics actions apply.
|
||||
final Map<CustomSemanticsAction, VoidCallback> semanticsActions = <CustomSemanticsAction, VoidCallback>{};
|
||||
|
||||
// Create the appropriate semantics actions.
|
||||
void moveToStart() => reorder(index, 0);
|
||||
void moveToEnd() => reorder(index, widget.children.length);
|
||||
void moveBefore() => reorder(index, index - 1);
|
||||
// To move after, we go to index+2 because we are moving it to the space
|
||||
// before index+2, which is after the space at index+1.
|
||||
void moveAfter() => reorder(index, index + 2);
|
||||
|
||||
final MaterialLocalizations localizations = MaterialLocalizations.of(context);
|
||||
|
||||
// If the item can move to before its current position in the list.
|
||||
if (index > 0) {
|
||||
semanticsActions[CustomSemanticsAction(label: localizations.reorderItemToStart)] = moveToStart;
|
||||
String reorderItemBefore = localizations.reorderItemUp;
|
||||
if (widget.scrollDirection == Axis.horizontal) {
|
||||
reorderItemBefore = Directionality.of(context) == TextDirection.ltr
|
||||
? localizations.reorderItemLeft
|
||||
: localizations.reorderItemRight;
|
||||
}
|
||||
semanticsActions[CustomSemanticsAction(label: reorderItemBefore)] = moveBefore;
|
||||
// If the item can move to after its current position in the list.
|
||||
if (index < widget.children.length - 1) {
|
||||
String reorderItemAfter = localizations.reorderItemDown;
|
||||
if (widget.scrollDirection == Axis.horizontal) {
|
||||
reorderItemAfter = Directionality.of(context) == TextDirection.ltr
|
||||
? localizations.reorderItemRight
|
||||
: localizations.reorderItemLeft;
|
||||
}
|
||||
|
||||
// If the item can move to after its current position in the list.
|
||||
if (index < widget.children.length - 1) {
|
||||
String reorderItemAfter = localizations.reorderItemDown;
|
||||
if (widget.scrollDirection == Axis.horizontal) {
|
||||
reorderItemAfter = Directionality.of(context) == TextDirection.ltr
|
||||
? localizations.reorderItemRight
|
||||
: localizations.reorderItemLeft;
|
||||
}
|
||||
semanticsActions[CustomSemanticsAction(label: reorderItemAfter)] = moveAfter;
|
||||
semanticsActions[CustomSemanticsAction(label: localizations.reorderItemToEnd)] = moveToEnd;
|
||||
}
|
||||
|
||||
// We pass toWrap with a GlobalKey into the Draggable so that when a list
|
||||
// item gets dragged, the accessibility framework can preserve the selected
|
||||
// state of the dragging item.
|
||||
//
|
||||
// We also apply the relevant custom accessibility actions for moving the item
|
||||
// up, down, to the start, and to the end of the list.
|
||||
return KeyedSubtree(
|
||||
key: keyIndexGlobalKey,
|
||||
child: MergeSemantics(
|
||||
child: Semantics(
|
||||
customSemanticsActions: semanticsActions,
|
||||
child: toWrap,
|
||||
),
|
||||
),
|
||||
);
|
||||
semanticsActions[CustomSemanticsAction(label: reorderItemAfter)] = moveAfter;
|
||||
semanticsActions[CustomSemanticsAction(label: localizations.reorderItemToEnd)] = moveToEnd;
|
||||
}
|
||||
|
||||
Widget buildDragTarget(BuildContext context, List<Key?> acceptedCandidates, List<dynamic> rejectedCandidates) {
|
||||
final Widget toWrapWithSemantics = wrapWithSemantics();
|
||||
// We pass toWrap with a GlobalKey into the item so that when it
|
||||
// gets dragged, the accessibility framework can preserve the selected
|
||||
// state of the dragging item.
|
||||
//
|
||||
// We also apply the relevant custom accessibility actions for moving the item
|
||||
// up, down, to the start, and to the end of the list.
|
||||
return MergeSemantics(
|
||||
child: Semantics(
|
||||
customSemanticsActions: semanticsActions,
|
||||
child: child,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// We build the draggable inside of a layout builder so that we can
|
||||
// constrain the size of the feedback dragging widget.
|
||||
Widget child = LongPressDraggable<Key>(
|
||||
maxSimultaneousDrags: 1,
|
||||
axis: widget.scrollDirection,
|
||||
data: toWrap.key,
|
||||
ignoringFeedbackSemantics: false,
|
||||
feedback: Container(
|
||||
alignment: Alignment.topLeft,
|
||||
// These constraints will limit the cross axis of the drawn widget.
|
||||
constraints: constraints,
|
||||
child: Material(
|
||||
elevation: 6.0,
|
||||
child: toWrapWithSemantics,
|
||||
),
|
||||
),
|
||||
child: _dragging == toWrap.key ? const SizedBox() : toWrapWithSemantics,
|
||||
childWhenDragging: const SizedBox(),
|
||||
dragAnchor: DragAnchor.child,
|
||||
onDragStarted: onDragStarted,
|
||||
// When the drag ends inside a DragTarget widget, the drag
|
||||
// succeeds, and we reorder the widget into position appropriately.
|
||||
onDragCompleted: onDragEnded,
|
||||
// When the drag does not end inside a DragTarget widget, the
|
||||
// drag fails, but we still reorder the widget to the last position it
|
||||
// had been dragged to.
|
||||
onDraggableCanceled: (Velocity velocity, Offset offset) {
|
||||
onDragEnded();
|
||||
},
|
||||
);
|
||||
Widget _itemBuilder(BuildContext context, int index) {
|
||||
final Widget item = widget.children[index];
|
||||
|
||||
// The target for dropping at the end of the list doesn't need to be
|
||||
// draggable.
|
||||
if (index >= widget.children.length) {
|
||||
child = toWrap;
|
||||
}
|
||||
// TODO(goderbauer): The semantics stuff should probably happen inside
|
||||
// _ReorderableItem so the widget versions can have them as well.
|
||||
final Widget itemWithSemantics = _wrapWithSemantics(item, index);
|
||||
final Key itemGlobalKey = _ReorderableListViewChildGlobalKey(item.key!, this);
|
||||
|
||||
// Determine the size of the drop area to show under the dragging widget.
|
||||
final Widget spacing;
|
||||
switch (widget.scrollDirection) {
|
||||
case Axis.horizontal:
|
||||
spacing = SizedBox(width: _dropAreaExtent);
|
||||
break;
|
||||
case Axis.vertical:
|
||||
spacing = SizedBox(height: _dropAreaExtent);
|
||||
break;
|
||||
}
|
||||
if (widget.buildDefaultDragHandles) {
|
||||
switch (Theme.of(context).platform) {
|
||||
case TargetPlatform.fuchsia:
|
||||
case TargetPlatform.linux:
|
||||
case TargetPlatform.windows:
|
||||
case TargetPlatform.macOS:
|
||||
return Stack(
|
||||
key: itemGlobalKey,
|
||||
children: <Widget>[
|
||||
itemWithSemantics,
|
||||
Positioned.directional(
|
||||
textDirection: Directionality.of(context),
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
end: 8,
|
||||
child: Align(
|
||||
alignment: AlignmentDirectional.centerEnd,
|
||||
child: ReorderableDragStartListener(
|
||||
index: index,
|
||||
child: const Icon(Icons.drag_handle),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
// We open up a space under where the dragging widget currently is to
|
||||
// show it can be dropped.
|
||||
if (_currentIndex == index) {
|
||||
return _buildContainerForScrollDirection(children: <Widget>[
|
||||
SizeTransition(
|
||||
sizeFactor: _entranceController,
|
||||
axis: widget.scrollDirection,
|
||||
child: spacing,
|
||||
),
|
||||
child,
|
||||
]);
|
||||
case TargetPlatform.iOS:
|
||||
case TargetPlatform.android:
|
||||
return ReorderableDelayedDragStartListener(
|
||||
key: itemGlobalKey,
|
||||
index: index,
|
||||
child: itemWithSemantics,
|
||||
);
|
||||
}
|
||||
// We close up the space under where the dragging widget previously was
|
||||
// with the ghostController animation.
|
||||
if (_ghostIndex == index) {
|
||||
return _buildContainerForScrollDirection(children: <Widget>[
|
||||
SizeTransition(
|
||||
sizeFactor: _ghostController,
|
||||
axis: widget.scrollDirection,
|
||||
child: spacing,
|
||||
),
|
||||
child,
|
||||
]);
|
||||
}
|
||||
return child;
|
||||
}
|
||||
|
||||
// We wrap the drag target in a Builder so that we can scroll to its specific context.
|
||||
return Builder(builder: (BuildContext context) {
|
||||
return DragTarget<Key>(
|
||||
builder: buildDragTarget,
|
||||
onWillAccept: (Key? toAccept) {
|
||||
setState(() {
|
||||
_nextIndex = index;
|
||||
_requestAnimationToNextIndex();
|
||||
});
|
||||
_scrollTo(context);
|
||||
// If the target is not the original starting point, then we will accept the drop.
|
||||
return _dragging == toAccept && toAccept != toWrap.key;
|
||||
},
|
||||
onAccept: (Key accepted) { },
|
||||
onLeave: (Object? leaving) { },
|
||||
);
|
||||
});
|
||||
return KeyedSubtree(
|
||||
key: itemGlobalKey,
|
||||
child: itemWithSemantics,
|
||||
);
|
||||
}
|
||||
|
||||
Widget _proxyDecorator(Widget child, int index, Animation<double> animation) {
|
||||
return AnimatedBuilder(
|
||||
animation: animation,
|
||||
builder: (BuildContext context, Widget? child) {
|
||||
final double animValue = Curves.easeInOut.transform(animation.value);
|
||||
final double elevation = lerpDouble(0, 6, animValue)!;
|
||||
return Material(
|
||||
child: child,
|
||||
elevation: elevation,
|
||||
);
|
||||
},
|
||||
child: child,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
assert(debugCheckHasMaterialLocalizations(context));
|
||||
// We use the layout builder to constrain the cross-axis size of dragging child widgets.
|
||||
return LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) {
|
||||
const Key endWidgetKey = Key('DraggableList - End Widget');
|
||||
final Widget finalDropArea;
|
||||
switch (widget.scrollDirection) {
|
||||
case Axis.horizontal:
|
||||
finalDropArea = SizedBox(
|
||||
key: endWidgetKey,
|
||||
width: _defaultDropAreaExtent,
|
||||
height: constraints.maxHeight,
|
||||
);
|
||||
break;
|
||||
case Axis.vertical:
|
||||
finalDropArea = SizedBox(
|
||||
key: endWidgetKey,
|
||||
height: _defaultDropAreaExtent,
|
||||
width: constraints.maxWidth,
|
||||
);
|
||||
break;
|
||||
}
|
||||
// If there is a header we can't just apply the padding to the list,
|
||||
// so we wrap the CustomScrollView in the padding for the top, left and right
|
||||
// and only add the padding from the bottom to the sliver list (or the equivalent
|
||||
// for other axis directions).
|
||||
final EdgeInsets padding = widget.padding ?? const EdgeInsets.all(0);
|
||||
late EdgeInsets outerPadding;
|
||||
late EdgeInsets listPadding;
|
||||
switch (widget.scrollDirection) {
|
||||
|
||||
// If the reorderable list only has one child element, reordering
|
||||
// should not be allowed.
|
||||
final bool hasMoreThanOneChildElement = widget.children.length > 1;
|
||||
case Axis.horizontal:
|
||||
if (widget.reverse) {
|
||||
outerPadding = EdgeInsets.fromLTRB(0, padding.top, padding.right, padding.bottom);
|
||||
listPadding = EdgeInsets.fromLTRB(padding.left, 0, 0, 0);
|
||||
} else {
|
||||
outerPadding = EdgeInsets.fromLTRB(padding.left, padding.top, 0, padding.bottom);
|
||||
listPadding = EdgeInsets.fromLTRB(0, 0, padding.right, 0);
|
||||
}
|
||||
break;
|
||||
case Axis.vertical:
|
||||
if (widget.reverse) {
|
||||
outerPadding = EdgeInsets.fromLTRB(padding.left, 0, padding.right, padding.bottom);
|
||||
listPadding = EdgeInsets.fromLTRB(0, padding.top, 0, 0);
|
||||
} else {
|
||||
outerPadding = EdgeInsets.fromLTRB(padding.left, padding.top, padding.right, 0);
|
||||
listPadding = EdgeInsets.fromLTRB(0, 0, 0, padding.bottom);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
return SingleChildScrollView(
|
||||
return Padding(
|
||||
padding: outerPadding,
|
||||
child: CustomScrollView(
|
||||
scrollDirection: widget.scrollDirection,
|
||||
padding: widget.padding,
|
||||
controller: _scrollController,
|
||||
reverse: widget.reverse,
|
||||
child: _buildContainerForScrollDirection(
|
||||
children: <Widget>[
|
||||
if (widget.reverse && hasMoreThanOneChildElement) _wrap(finalDropArea, widget.children.length, constraints),
|
||||
if (widget.header != null) widget.header!,
|
||||
for (int i = 0; i < widget.children.length; i += 1) _wrap(widget.children[i], i, constraints),
|
||||
if (!widget.reverse && hasMoreThanOneChildElement) _wrap(finalDropArea, widget.children.length, constraints),
|
||||
],
|
||||
),
|
||||
);
|
||||
});
|
||||
controller: widget.scrollController,
|
||||
slivers: <Widget>[
|
||||
if (widget.header != null)
|
||||
SliverToBoxAdapter(child: widget.header!),
|
||||
SliverPadding(
|
||||
padding: listPadding,
|
||||
sliver: SliverReorderableList(
|
||||
itemBuilder: _itemBuilder,
|
||||
itemCount: widget.children.length,
|
||||
onReorder: widget.onReorder,
|
||||
proxyDecorator: widget.proxyDecorator ?? _proxyDecorator,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -631,12 +475,10 @@ class _ReorderableListContentState extends State<_ReorderableListContent> with T
|
||||
// of the objects used to generate widgets.
|
||||
@optionalTypeArgs
|
||||
class _ReorderableListViewChildGlobalKey extends GlobalObjectKey {
|
||||
|
||||
const _ReorderableListViewChildGlobalKey(this.subKey, this.state) : super(subKey);
|
||||
|
||||
final Key subKey;
|
||||
|
||||
final _ReorderableListContentState state;
|
||||
final State state;
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
|
||||
@@ -11,6 +11,7 @@ import 'basic.dart';
|
||||
import 'framework.dart';
|
||||
import 'localizations.dart';
|
||||
import 'media_query.dart';
|
||||
import 'overlay.dart';
|
||||
import 'table.dart';
|
||||
|
||||
// Any changes to this file should be reflected in the debugAssertAllWidgetVarsUnset()
|
||||
@@ -363,6 +364,40 @@ bool debugCheckHasWidgetsLocalizations(BuildContext context) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Asserts that the given context has an [Overlay] ancestor.
|
||||
///
|
||||
/// To call this function, use the following pattern, typically in the
|
||||
/// relevant Widget's build method:
|
||||
///
|
||||
/// ```dart
|
||||
/// assert(debugCheckHasOverlay(context));
|
||||
/// ```
|
||||
///
|
||||
/// Does nothing if asserts are disabled. Always returns true.
|
||||
bool debugCheckHasOverlay(BuildContext context) {
|
||||
assert(() {
|
||||
if (context.widget is! Overlay && context.findAncestorWidgetOfExactType<Overlay>() == null) {
|
||||
throw FlutterError.fromParts(<DiagnosticsNode>[
|
||||
ErrorSummary('No Overlay widget found.'),
|
||||
ErrorDescription(
|
||||
'${context.widget.runtimeType} widgets require an Overlay '
|
||||
'widget ancestor.\n'
|
||||
'An overlay lets widgets float on top of other widget children.'
|
||||
),
|
||||
ErrorHint(
|
||||
'To introduce an Overlay widget, you can either directly '
|
||||
'include one, or use a widget that contains an Overlay itself, '
|
||||
'such as a Navigator, WidgetApp, MaterialApp, or CupertinoApp.',
|
||||
),
|
||||
...context.describeMissingAncestor(expectedAncestorType: Overlay)
|
||||
]
|
||||
);
|
||||
}
|
||||
return true;
|
||||
}());
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Returns true if none of the widget library debug variables have been changed.
|
||||
///
|
||||
/// This function is used by the test framework to ensure that debug variables
|
||||
|
||||
1288
packages/flutter/lib/src/widgets/reorderable_list.dart
Normal file
1288
packages/flutter/lib/src/widgets/reorderable_list.dart
Normal file
File diff suppressed because it is too large
Load Diff
@@ -83,6 +83,7 @@ export 'src/widgets/platform_view.dart';
|
||||
export 'src/widgets/preferred_size.dart';
|
||||
export 'src/widgets/primary_scroll_controller.dart';
|
||||
export 'src/widgets/raw_keyboard_listener.dart';
|
||||
export 'src/widgets/reorderable_list.dart';
|
||||
export 'src/widgets/restoration.dart';
|
||||
export 'src/widgets/restoration_properties.dart';
|
||||
export 'src/widgets/router.dart';
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'package:flutter/rendering.dart';
|
||||
import 'package:flutter/semantics.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
@@ -90,6 +91,7 @@ void main() {
|
||||
await drag.moveTo(tester.getCenter(find.text('Item 4')));
|
||||
expect(listItems, orderedEquals(originalListItems));
|
||||
await drag.up();
|
||||
await tester.pumpAndSettle();
|
||||
expect(listItems, orderedEquals(<String>['Item 2', 'Item 3', 'Item 1', 'Item 4']));
|
||||
});
|
||||
|
||||
@@ -101,6 +103,7 @@ void main() {
|
||||
tester.getCenter(find.text('Item 1')),
|
||||
tester.getCenter(find.text('Item 4')) + const Offset(0.0, itemHeight * 2),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(listItems, orderedEquals(<String>['Item 2', 'Item 3', 'Item 4', 'Item 1']));
|
||||
});
|
||||
|
||||
@@ -112,6 +115,7 @@ void main() {
|
||||
tester.getCenter(find.text('Item 4')),
|
||||
tester.getCenter(find.text('Item 1')),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(listItems, orderedEquals(<String>['Item 4', 'Item 1', 'Item 2', 'Item 3']));
|
||||
});
|
||||
|
||||
@@ -123,6 +127,7 @@ void main() {
|
||||
tester.getCenter(find.text('Item 3')),
|
||||
tester.getCenter(find.text('Item 2')),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(listItems, orderedEquals(<String>['Item 1', 'Item 3', 'Item 2', 'Item 4']));
|
||||
});
|
||||
|
||||
@@ -135,6 +140,7 @@ void main() {
|
||||
tester.getCenter(find.text('Item 1')),
|
||||
tester.getCenter(find.text('Item 4')) + const Offset(0.0, itemHeight * 2),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Header Text'), findsOneWidget);
|
||||
expect(listItems, orderedEquals(<String>['Item 2', 'Item 3', 'Item 4', 'Item 1']));
|
||||
});
|
||||
@@ -168,45 +174,43 @@ void main() {
|
||||
),
|
||||
));
|
||||
|
||||
Element getContentElement() {
|
||||
final SingleChildScrollView listScrollView = tester.widget(find.byType(SingleChildScrollView));
|
||||
final Widget scrollContents = listScrollView.child!;
|
||||
final Element contentElement = tester.element(find.byElementPredicate((Element element) => element.widget == scrollContents));
|
||||
return contentElement;
|
||||
double getListHeight() {
|
||||
final RenderSliverList listScrollView = tester.renderObject(find.byType(SliverList));
|
||||
return listScrollView.geometry!.maxPaintExtent;
|
||||
}
|
||||
|
||||
const double kDraggingListHeight = 292.0;
|
||||
const double kDraggingListHeight = 4 * itemHeight;
|
||||
// Drag a normal text item
|
||||
expect(getContentElement().size!.height, kDraggingListHeight);
|
||||
expect(getListHeight(), kDraggingListHeight);
|
||||
TestGesture drag = await tester.startGesture(tester.getCenter(find.text('Normal item')));
|
||||
await tester.pump(kLongPressTimeout + kPressTimeout);
|
||||
await tester.pumpAndSettle();
|
||||
expect(getContentElement().size!.height, kDraggingListHeight);
|
||||
expect(getListHeight(), kDraggingListHeight);
|
||||
|
||||
// Move it
|
||||
await drag.moveTo(tester.getCenter(find.text('Last item')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(getContentElement().size!.height, kDraggingListHeight);
|
||||
expect(getListHeight(), kDraggingListHeight);
|
||||
|
||||
// Drop it
|
||||
await drag.up();
|
||||
await tester.pumpAndSettle();
|
||||
expect(getContentElement().size!.height, kDraggingListHeight);
|
||||
expect(getListHeight(), kDraggingListHeight);
|
||||
|
||||
// Drag a tall item
|
||||
drag = await tester.startGesture(tester.getCenter(find.text('Tall item')));
|
||||
await tester.pump(kLongPressTimeout + kPressTimeout);
|
||||
await tester.pumpAndSettle();
|
||||
expect(getContentElement().size!.height, kDraggingListHeight);
|
||||
expect(getListHeight(), kDraggingListHeight);
|
||||
// Move it
|
||||
await drag.moveTo(tester.getCenter(find.text('Last item')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(getContentElement().size!.height, kDraggingListHeight);
|
||||
expect(getListHeight(), kDraggingListHeight);
|
||||
|
||||
// Drop it
|
||||
await drag.up();
|
||||
await tester.pumpAndSettle();
|
||||
expect(getContentElement().size!.height, kDraggingListHeight);
|
||||
expect(getListHeight(), kDraggingListHeight);
|
||||
});
|
||||
|
||||
testWidgets('Vertical drop area golden', (WidgetTester tester) async {
|
||||
@@ -344,8 +348,8 @@ void main() {
|
||||
}
|
||||
|
||||
await tester.pumpWidget(buildWithScrollController(primary));
|
||||
SingleChildScrollView scrollView = tester.widget(
|
||||
find.byType(SingleChildScrollView),
|
||||
Scrollable scrollView = tester.widget(
|
||||
find.byType(Scrollable),
|
||||
);
|
||||
expect(scrollView.controller, primary);
|
||||
|
||||
@@ -353,7 +357,7 @@ void main() {
|
||||
final ScrollController primary2 = ScrollController();
|
||||
await tester.pumpWidget(buildWithScrollController(primary2));
|
||||
scrollView = tester.widget(
|
||||
find.byType(SingleChildScrollView),
|
||||
find.byType(Scrollable),
|
||||
);
|
||||
expect(scrollView.controller, primary2);
|
||||
});
|
||||
@@ -367,7 +371,7 @@ void main() {
|
||||
MaterialApp(
|
||||
home: Scaffold(
|
||||
body: SizedBox(
|
||||
height: 200,
|
||||
height: 150,
|
||||
child: ReorderableListView(
|
||||
scrollController: customController,
|
||||
onReorder: (int oldIndex, int newIndex) { },
|
||||
@@ -414,6 +418,9 @@ void main() {
|
||||
// First 20.0 px always ignored, so scroll offset is only
|
||||
// shifted by 80.0.
|
||||
// Final offset: 40.0 + 80.0 = 120.0
|
||||
// The total distance available to scroll is 300.0 - 150.0 = 150.0, or
|
||||
// height of the ReorderableListView minus height of the SizedBox. Since
|
||||
// The final offset is less than this, it's not limited.
|
||||
expect(customController.offset, 120.0);
|
||||
});
|
||||
|
||||
@@ -446,11 +453,6 @@ void main() {
|
||||
} catch (e) {
|
||||
fail('Expected no error, but got $e');
|
||||
}
|
||||
// Expect that we have build *a* ScrollController for use in the view.
|
||||
final SingleChildScrollView scrollView = tester.widget(
|
||||
find.byType(SingleChildScrollView),
|
||||
);
|
||||
expect(scrollView.controller, isNotNull);
|
||||
});
|
||||
|
||||
group('Accessibility (a11y/Semantics)', () {
|
||||
@@ -675,6 +677,7 @@ void main() {
|
||||
tester.getCenter(find.text('Item 1')),
|
||||
tester.getCenter(find.text('Item 4')) + const Offset(itemHeight * 2, 0.0),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(listItems, orderedEquals(<String>['Item 2', 'Item 3', 'Item 4', 'Item 1']));
|
||||
});
|
||||
|
||||
@@ -686,6 +689,7 @@ void main() {
|
||||
tester.getCenter(find.text('Item 4')),
|
||||
tester.getCenter(find.text('Item 1')),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(listItems, orderedEquals(<String>['Item 4', 'Item 1', 'Item 2', 'Item 3']));
|
||||
});
|
||||
|
||||
@@ -697,6 +701,7 @@ void main() {
|
||||
tester.getCenter(find.text('Item 3')),
|
||||
tester.getCenter(find.text('Item 2')),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(listItems, orderedEquals(<String>['Item 1', 'Item 3', 'Item 2', 'Item 4']));
|
||||
});
|
||||
|
||||
@@ -718,6 +723,7 @@ void main() {
|
||||
tester.getCenter(find.text('Item 4')),
|
||||
tester.getCenter(find.text('Item 3')),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Header Text'), findsOneWidget);
|
||||
expect(listItems, orderedEquals(<String>['Item 2', 'Item 4', 'Item 3', 'Item 1']));
|
||||
});
|
||||
@@ -751,45 +757,43 @@ void main() {
|
||||
),
|
||||
));
|
||||
|
||||
Element getContentElement() {
|
||||
final SingleChildScrollView listScrollView = tester.widget(find.byType(SingleChildScrollView));
|
||||
final Widget scrollContents = listScrollView.child!;
|
||||
final Element contentElement = tester.element(find.byElementPredicate((Element element) => element.widget == scrollContents));
|
||||
return contentElement;
|
||||
double getListWidth() {
|
||||
final RenderSliverList listScrollView = tester.renderObject(find.byType(SliverList));
|
||||
return listScrollView.geometry!.maxPaintExtent;
|
||||
}
|
||||
|
||||
const double kDraggingListWidth = 292.0;
|
||||
const double kDraggingListWidth = 4 * itemHeight;
|
||||
// Drag a normal text item
|
||||
expect(getContentElement().size!.width, kDraggingListWidth);
|
||||
expect(getListWidth(), kDraggingListWidth);
|
||||
TestGesture drag = await tester.startGesture(tester.getCenter(find.text('Normal item')));
|
||||
await tester.pump(kLongPressTimeout + kPressTimeout);
|
||||
await tester.pumpAndSettle();
|
||||
expect(getContentElement().size!.width, kDraggingListWidth);
|
||||
expect(getListWidth(), kDraggingListWidth);
|
||||
|
||||
// Move it
|
||||
await drag.moveTo(tester.getCenter(find.text('Last item')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(getContentElement().size!.width, kDraggingListWidth);
|
||||
expect(getListWidth(), kDraggingListWidth);
|
||||
|
||||
// Drop it
|
||||
await drag.up();
|
||||
await tester.pumpAndSettle();
|
||||
expect(getContentElement().size!.width, kDraggingListWidth);
|
||||
expect(getListWidth(), kDraggingListWidth);
|
||||
|
||||
// Drag a tall item
|
||||
drag = await tester.startGesture(tester.getCenter(find.text('Tall item')));
|
||||
await tester.pump(kLongPressTimeout + kPressTimeout);
|
||||
await tester.pumpAndSettle();
|
||||
expect(getContentElement().size!.width, kDraggingListWidth);
|
||||
expect(getListWidth(), kDraggingListWidth);
|
||||
// Move it
|
||||
await drag.moveTo(tester.getCenter(find.text('Last item')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(getContentElement().size!.width, kDraggingListWidth);
|
||||
expect(getListWidth(), kDraggingListWidth);
|
||||
|
||||
// Drop it
|
||||
await drag.up();
|
||||
await tester.pumpAndSettle();
|
||||
expect(getContentElement().size!.width, kDraggingListWidth);
|
||||
expect(getListWidth(), kDraggingListWidth);
|
||||
});
|
||||
|
||||
testWidgets('Horizontal drop area golden', (WidgetTester tester) async {
|
||||
@@ -1171,7 +1175,7 @@ void main() {
|
||||
await tester.pumpWidget(MaterialApp(
|
||||
home: reorderableListView,
|
||||
));
|
||||
expect(tester.getCenter(find.text('A')).dy, lessThan(tester.getCenter(find.text('B')).dy));
|
||||
expect(tester.getCenter(find.text('A')).dy, greaterThan(tester.getCenter(find.text('B')).dy));
|
||||
});
|
||||
|
||||
testWidgets('Animation test when placing an item in place', (WidgetTester tester) async {
|
||||
|
||||
198
packages/flutter/test/widgets/reorderable_list_test.dart
Normal file
198
packages/flutter/test/widgets/reorderable_list_test.dart
Normal file
@@ -0,0 +1,198 @@
|
||||
// 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_test/flutter_test.dart';
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
void main() {
|
||||
testWidgets('SliverReorderableList, drag and drop, fixed height items', (WidgetTester tester) async {
|
||||
final List<int> items = List<int>.generate(8, (int index) => index);
|
||||
|
||||
Future<void> pressDragRelease(Offset start, Offset delta) async {
|
||||
final TestGesture drag = await tester.startGesture(start);
|
||||
await tester.pump(kPressTimeout);
|
||||
await drag.moveBy(delta);
|
||||
await tester.pump(kPressTimeout);
|
||||
await drag.up();
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
void check({ List<int> visible = const <int>[], List<int> hidden = const <int>[] }) {
|
||||
for (final int i in visible) {
|
||||
expect(find.text('item $i'), findsOneWidget);
|
||||
}
|
||||
for (final int i in hidden) {
|
||||
expect(find.text('item $i'), findsNothing);
|
||||
}
|
||||
}
|
||||
|
||||
// The SliverReorderableList is 800x600, 8 items, each item is 800x100 with
|
||||
// an "item $index" text widget at the item's origin. Drags are initiated by
|
||||
// a simple press on the text widget.
|
||||
await tester.pumpWidget(TestList(items: items));
|
||||
check(visible: <int>[0, 1, 2, 3, 4, 5], hidden: <int>[6, 7]);
|
||||
|
||||
// Drag item 0 downwards less than halfway and let it snap back. List
|
||||
// should remain as it is.
|
||||
await pressDragRelease(const Offset(12, 50), const Offset(12, 60));
|
||||
check(visible: <int>[0, 1, 2, 3, 4, 5], hidden: <int>[6, 7]);
|
||||
expect(tester.getTopLeft(find.text('item 0')), Offset.zero);
|
||||
expect(tester.getTopLeft(find.text('item 1')), const Offset(0, 100));
|
||||
expect(items, orderedEquals(<int>[0, 1, 2, 3, 4, 5, 6, 7]));
|
||||
|
||||
// Drag item 0 downwards more than halfway to displace item 1.
|
||||
await pressDragRelease(tester.getCenter(find.text('item 0')), const Offset(0, 151));
|
||||
check(visible: <int>[0, 1, 2, 3, 4, 5], hidden: <int>[6, 7]);
|
||||
expect(tester.getTopLeft(find.text('item 1')), Offset.zero);
|
||||
expect(tester.getTopLeft(find.text('item 0')), const Offset(0, 100));
|
||||
expect(items, orderedEquals(<int>[1, 0, 2, 3, 4, 5, 6, 7]));
|
||||
|
||||
// Drag item 0 back to where it was.
|
||||
await pressDragRelease(tester.getCenter(find.text('item 0')), const Offset(0, -51));
|
||||
check(visible: <int>[0, 1, 2, 3, 4, 5], hidden: <int>[6, 7]);
|
||||
expect(tester.getTopLeft(find.text('item 0')), Offset.zero);
|
||||
expect(tester.getTopLeft(find.text('item 1')), const Offset(0, 100));
|
||||
expect(items, orderedEquals(<int>[0, 1, 2, 3, 4, 5, 6, 7]));
|
||||
|
||||
// Drag item 1 to item 3
|
||||
await pressDragRelease(tester.getCenter(find.text('item 1')), const Offset(0, 251));
|
||||
check(visible: <int>[0, 1, 2, 3, 4, 5], hidden: <int>[6, 7]);
|
||||
expect(tester.getTopLeft(find.text('item 0')), Offset.zero);
|
||||
expect(tester.getTopLeft(find.text('item 1')), const Offset(0, 300));
|
||||
expect(tester.getTopLeft(find.text('item 3')), const Offset(0, 200));
|
||||
expect(items, orderedEquals(<int>[0, 2, 3, 1, 4, 5, 6, 7]));
|
||||
|
||||
// Drag item 1 back to where it was
|
||||
await pressDragRelease(tester.getCenter(find.text('item 1')), const Offset(0, -200));
|
||||
check(visible: <int>[0, 1, 2, 3, 4, 5], hidden: <int>[6, 7]);
|
||||
expect(tester.getTopLeft(find.text('item 0')), Offset.zero);
|
||||
expect(tester.getTopLeft(find.text('item 1')), const Offset(0, 100));
|
||||
expect(tester.getTopLeft(find.text('item 3')), const Offset(0, 300));
|
||||
expect(items, orderedEquals(<int>[0, 1, 2, 3, 4, 5, 6, 7]));
|
||||
});
|
||||
|
||||
testWidgets('SliverReorderableList, items inherit DefaultTextStyle, IconTheme', (WidgetTester tester) async {
|
||||
const Color textColor = Color(0xffffffff);
|
||||
const Color iconColor = Color(0xff0000ff);
|
||||
|
||||
TextStyle getIconStyle() {
|
||||
return tester.widget<RichText>(
|
||||
find.descendant(
|
||||
of: find.byType(Icon),
|
||||
matching: find.byType(RichText),
|
||||
),
|
||||
).text.style!;
|
||||
}
|
||||
|
||||
TextStyle getTextStyle() {
|
||||
return tester.widget<RichText>(
|
||||
find.descendant(
|
||||
of: find.text('item 0'),
|
||||
matching: find.byType(RichText),
|
||||
),
|
||||
).text.style!;
|
||||
}
|
||||
|
||||
// This SliverReorderableList has just one item: "item 0".
|
||||
await tester.pumpWidget(
|
||||
TestList(
|
||||
items: List<int>.from(<int>[0]),
|
||||
textColor: textColor,
|
||||
iconColor: iconColor,
|
||||
),
|
||||
);
|
||||
expect(tester.getTopLeft(find.text('item 0')), Offset.zero);
|
||||
expect(getIconStyle().color, iconColor);
|
||||
expect(getTextStyle().color, textColor);
|
||||
|
||||
// Dragging item 0 causes it to be reparented in the overlay. The item
|
||||
// should still inherit the IconTheme and DefaultTextStyle because they are
|
||||
// InheritedThemes.
|
||||
final TestGesture drag = await tester.startGesture(tester.getCenter(find.text('item 0')));
|
||||
await tester.pump(kPressTimeout);
|
||||
await drag.moveBy(const Offset(0, 50));
|
||||
await tester.pump(kPressTimeout);
|
||||
expect(tester.getTopLeft(find.text('item 0')), const Offset(0, 50));
|
||||
expect(getIconStyle().color, iconColor);
|
||||
expect(getTextStyle().color, textColor);
|
||||
|
||||
// Drag is complete, item 0 returns to where it was.
|
||||
await drag.up();
|
||||
await tester.pumpAndSettle();
|
||||
expect(tester.getTopLeft(find.text('item 0')), Offset.zero);
|
||||
expect(getIconStyle().color, iconColor);
|
||||
expect(getTextStyle().color, textColor);
|
||||
});
|
||||
}
|
||||
|
||||
class TestList extends StatefulWidget {
|
||||
const TestList({
|
||||
Key? key,
|
||||
this.textColor,
|
||||
this.iconColor,
|
||||
required this.items,
|
||||
}) : super(key: key);
|
||||
|
||||
final List<int> items;
|
||||
final Color? textColor;
|
||||
final Color? iconColor;
|
||||
|
||||
@override
|
||||
_TestListState createState() => _TestListState();
|
||||
}
|
||||
|
||||
class _TestListState extends State<TestList> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MaterialApp(
|
||||
home: Scaffold(
|
||||
body: DefaultTextStyle(
|
||||
style: TextStyle(color: widget.textColor),
|
||||
child: IconTheme(
|
||||
data: IconThemeData(color: widget.iconColor),
|
||||
child: StatefulBuilder(
|
||||
builder: (BuildContext outerContext, StateSetter setState) {
|
||||
final List<int> items = widget.items;
|
||||
return CustomScrollView(
|
||||
slivers: <Widget>[
|
||||
SliverReorderableList(
|
||||
itemBuilder: (BuildContext context, int index) {
|
||||
return Container(
|
||||
key: ValueKey<int>(items[index]),
|
||||
height: 100,
|
||||
color: items[index].isOdd ? Colors.red : Colors.green,
|
||||
child: ReorderableDragStartListener(
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Text('item ${items[index]}'),
|
||||
const Icon(Icons.drag_handle),
|
||||
],
|
||||
),
|
||||
index: index,
|
||||
),
|
||||
);
|
||||
},
|
||||
itemCount: items.length,
|
||||
onReorder: (int fromIndex, int toIndex) {
|
||||
setState(() {
|
||||
if (toIndex > fromIndex) {
|
||||
toIndex -= 1;
|
||||
}
|
||||
items.insert(toIndex, items.removeAt(fromIndex));
|
||||
});
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user