reorderable_list.dart 19.9 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'dart:ui' show lerpDouble;
6

7
import 'package:flutter/gestures.dart';
8
import 'package:flutter/rendering.dart';
9
import 'package:flutter/widgets.dart';
10

11
import 'debug.dart';
12
import 'icons.dart';
13
import 'material.dart';
14
import 'material_localizations.dart';
15
import 'theme.dart';
16 17 18

/// A list whose items the user can interactively reorder by dragging.
///
19
/// {@youtube 560 315 https://www.youtube.com/watch?v=3fB1mxOsqJE}
20 21 22 23 24
///
/// This sample shows by dragging the user can reorder the items of the list.
/// The [onReorder] parameter is required and will be called when a child
/// widget is dragged to a new position.
///
25
/// {@tool dartpad}
26
///
27
/// ** See code in examples/api/lib/material/reorderable_list/reorderable_list_view.0.dart **
28 29
/// {@end-tool}
///
30 31 32 33 34 35 36 37 38 39 40
/// By default, on [TargetPlatformVariant.desktop] platforms each item will
/// have a drag handle added on top of it that will allow the user to grab it
/// to move the item. On [TargetPlatformVariant.mobile], no drag handle will be
/// added, but when the user long presses anywhere on the item it will start
/// moving the item. Displaying drag handles can be controlled with
/// [ReorderableListView.buildDefaultDragHandles].
///
/// All list items must have a key.
///
/// This example demonstrates using the [proxyDecorator] callback to customize
/// the appearance of a list item while it's being dragged.
41 42
/// {@tool snippet}
///
43 44 45 46 47
/// While a drag is underway, the widget returned by the [proxyDecorator]
/// serves as a "proxy" (a substitute) for the item in the list. The proxy is
/// created with the original list item as its child. The [proxyDecorator]
/// in this example is similar to the default one except that it changes the
/// proxy item's background color.
48 49 50
///
/// ** See code in examples/api/lib/material/reorderable_list/reorderable_list_view.1.dart **
/// {@end-tool}
51
class ReorderableListView extends StatefulWidget {
52 53
  /// Creates a reorderable list from a pre-built list of widgets.
  ///
54 55 56 57 58
  /// This constructor is appropriate for lists with a small number of
  /// children because constructing the [List] requires doing work for every
  /// child that could possibly be displayed in the list view instead of just
  /// those children that are actually visible.
  ///
59 60 61 62
  /// See also:
  ///
  ///   * [ReorderableListView.builder], which allows you to build a reorderable
  ///     list where the items are built as needed when scrolling the list.
63
  ReorderableListView({
64
    Key? key,
65
    required List<Widget> children,
66
    required this.onReorder,
67 68
    this.onReorderStart,
    this.onReorderEnd,
69
    this.itemExtent,
70
    this.prototypeItem,
71 72
    this.proxyDecorator,
    this.buildDefaultDragHandles = true,
73
    this.padding,
74
    this.header,
75
    this.footer,
76
    this.scrollDirection = Axis.vertical,
77
    this.reverse = false,
78 79 80 81 82 83 84 85 86 87
    this.scrollController,
    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,
88 89 90
  }) : assert(scrollDirection != null),
       assert(onReorder != null),
       assert(children != null),
91 92 93 94
       assert(
         itemExtent == null || prototypeItem == null,
         'You can only pass itemExtent or prototypeItem, not both',
       ),
95 96 97
       assert(
         children.every((Widget w) => w.key != null),
         'All children of this widget must have a key.',
98
       ),
99
       assert(buildDefaultDragHandles != null),
100 101
       itemBuilder = ((BuildContext context, int index) => children[index]),
       itemCount = children.length,
102
       super(key: key);
103

104
  /// Creates a reorderable list from widget items that are created on demand.
105
  ///
106 107 108
  /// This constructor is appropriate for list views with a large number of
  /// children because the builder is called only for those children
  /// that are actually visible.
109
  ///
110 111
  /// The `itemBuilder` callback will be called only with indices greater than
  /// or equal to zero and less than `itemCount`.
112
  ///
113 114 115 116 117 118 119
  /// The `itemBuilder` should always return a non-null widget, and actually
  /// create the widget instances when called. Avoid using a builder that
  /// returns a previously-constructed widget; if the list view's children are
  /// created in advance, or all at once when the [ReorderableListView] itself
  /// is created, it is more efficient to use the [ReorderableListView]
  /// constructor. Even more efficient, however, is to create the instances
  /// on demand using this constructor's `itemBuilder` callback.
120
  ///
121 122 123
  /// This example creates a list using the
  /// [ReorderableListView.builder] constructor. Using the [IndexedWidgetBuilder], The
  /// list items are built lazily on demand.
124
  /// {@tool dartpad}
125
  ///
126
  /// ** See code in examples/api/lib/material/reorderable_list/reorderable_list_view.reorderable_list_view_builder.0.dart **
127
  /// {@end-tool}
128
  /// See also:
129
  ///
130 131 132 133 134 135 136
  ///   * [ReorderableListView], which allows you to build a reorderable
  ///     list with all the items passed into the constructor.
  const ReorderableListView.builder({
    Key? key,
    required this.itemBuilder,
    required this.itemCount,
    required this.onReorder,
137 138
    this.onReorderStart,
    this.onReorderEnd,
139
    this.itemExtent,
140
    this.prototypeItem,
141 142 143 144
    this.proxyDecorator,
    this.buildDefaultDragHandles = true,
    this.padding,
    this.header,
145
    this.footer,
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
    this.scrollDirection = Axis.vertical,
    this.reverse = false,
    this.scrollController,
    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(scrollDirection != null),
       assert(itemCount >= 0),
       assert(onReorder != null),
161 162 163 164
       assert(
         itemExtent == null || prototypeItem == null,
         'You can only pass itemExtent or prototypeItem, not both',
       ),
165 166
       assert(buildDefaultDragHandles != null),
       super(key: key);
167

168 169 170 171 172 173 174
  /// {@macro flutter.widgets.reorderable_list.itemBuilder}
  final IndexedWidgetBuilder itemBuilder;

  /// {@macro flutter.widgets.reorderable_list.itemCount}
  final int itemCount;

  /// {@macro flutter.widgets.reorderable_list.onReorder}
Ian Hickson's avatar
Ian Hickson committed
175
  final ReorderCallback onReorder;
176

177 178 179 180 181 182
  /// {@macro flutter.widgets.reorderable_list.onReorderStart}
  final void Function(int index)? onReorderStart;

  /// {@macro flutter.widgets.reorderable_list.onReorderEnd}
  final void Function(int index)? onReorderEnd;

183 184 185
  /// {@macro flutter.widgets.reorderable_list.proxyDecorator}
  final ReorderItemProxyDecorator? proxyDecorator;

186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
  /// 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.
  ///
204
  /// {@tool dartpad}
205 206
  ///
  ///
207
  /// ** See code in examples/api/lib/material/reorderable_list/reorderable_list_view.build_default_drag_handles.0.dart **
208 209 210
  ///{@end-tool}
  final bool buildDefaultDragHandles;

211 212 213 214
  /// {@macro flutter.widgets.reorderable_list.padding}
  final EdgeInsets? padding;

  /// A non-reorderable header item to show before the items of the list.
215
  ///
216 217 218
  /// If null, no header will appear before the list.
  final Widget? header;

219 220 221 222 223
  /// A non-reorderable footer item to show after the items of the list.
  ///
  /// If null, no footer will appear after the list.
  final Widget? footer;

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
  /// {@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? scrollController;

  /// {@macro flutter.widgets.scroll_view.primary}

  /// Defaults to true when [scrollDirection] is [Axis.vertical] and
  /// [scrollController] is null.
  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;
266

267 268 269
  /// {@macro flutter.widgets.list_view.itemExtent}
  final double? itemExtent;

270 271 272
  /// {@macro flutter.widgets.list_view.prototypeItem}
  final Widget? prototypeItem;

273
  @override
274
  State<ReorderableListView> createState() => _ReorderableListViewState();
275 276 277
}

class _ReorderableListViewState extends State<ReorderableListView> {
278 279 280 281
  Widget _wrapWithSemantics(Widget child, int index) {
    void reorder(int startIndex, int endIndex) {
      if (startIndex != endIndex)
        widget.onReorder(startIndex, endIndex);
282 283
    }

284 285 286 287 288
    // First, determine which semantics actions apply.
    final Map<CustomSemanticsAction, VoidCallback> semanticsActions = <CustomSemanticsAction, VoidCallback>{};

    // Create the appropriate semantics actions.
    void moveToStart() => reorder(index, 0);
289
    void moveToEnd() => reorder(index, widget.itemCount);
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
    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;
305
      }
306
      semanticsActions[CustomSemanticsAction(label: reorderItemBefore)] = moveBefore;
307 308
    }

309
    // If the item can move to after its current position in the list.
310
    if (index < widget.itemCount - 1) {
311 312 313 314 315 316 317 318
      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;
319 320
    }

321 322 323 324 325 326 327 328 329 330 331
    // 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,
      ),
332 333 334
    );
  }

335
  Widget _itemBuilder(BuildContext context, int index) {
336
    final Widget item = widget.itemBuilder(context, index);
337 338 339
    assert(() {
      if (item.key == null) {
        throw FlutterError(
340
          'Every item of ReorderableListView must have a key.',
341 342 343 344
        );
      }
      return true;
    }());
345 346 347 348 349 350 351 352 353 354 355

    // 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);

    if (widget.buildDefaultDragHandles) {
      switch (Theme.of(context).platform) {
        case TargetPlatform.linux:
        case TargetPlatform.windows:
        case TargetPlatform.macOS:
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
          switch (widget.scrollDirection) {
            case Axis.horizontal:
              return Stack(
                key: itemGlobalKey,
                children: <Widget>[
                  itemWithSemantics,
                  Positioned.directional(
                    textDirection: Directionality.of(context),
                    start: 0,
                    end: 0,
                    bottom: 8,
                    child: Align(
                      alignment: AlignmentDirectional.bottomCenter,
                      child: ReorderableDragStartListener(
                        index: index,
                        child: const Icon(Icons.drag_handle),
                      ),
                    ),
374
                  ),
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
                ],
              );
            case Axis.vertical:
              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),
                      ),
                    ),
                  ),
                ],
              );
          }
398

399 400
        case TargetPlatform.iOS:
        case TargetPlatform.android:
401
        case TargetPlatform.fuchsia:
402 403 404 405 406
          return ReorderableDelayedDragStartListener(
            key: itemGlobalKey,
            index: index,
            child: itemWithSemantics,
          );
407 408 409
      }
    }

410 411 412 413 414
    return KeyedSubtree(
      key: itemGlobalKey,
      child: itemWithSemantics,
    );
  }
415

416 417 418 419 420 421 422 423
  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(
          elevation: elevation,
424
          child: child,
425 426 427 428
        );
      },
      child: child,
    );
429 430 431 432
  }

  @override
  Widget build(BuildContext context) {
433 434 435
    assert(debugCheckHasMaterialLocalizations(context));
    assert(debugCheckHasOverlay(context));

436 437
    // If there is a header or footer we can't just apply the padding to the list,
    // so we break it up into padding for the header, footer and padding for the list.
438
    final EdgeInsets padding = widget.padding ?? EdgeInsets.zero;
439
    late final EdgeInsets headerPadding;
440
    late final EdgeInsets footerPadding;
441 442
    late final EdgeInsets listPadding;

443
    if (widget.header == null && widget.footer == null) {
444
      headerPadding = EdgeInsets.zero;
445
      footerPadding = EdgeInsets.zero;
446
      listPadding = padding;
447
    } else if (widget.header != null || widget.footer != null) {
448 449 450 451
      switch (widget.scrollDirection) {
        case Axis.horizontal:
          if (widget.reverse) {
            headerPadding = EdgeInsets.fromLTRB(0, padding.top, padding.right, padding.bottom);
452 453
            listPadding = EdgeInsets.fromLTRB(widget.footer != null ? 0 : padding.left, padding.top, widget.header != null ? 0 : padding.right, padding.bottom);
            footerPadding = EdgeInsets.fromLTRB(padding.left, padding.top, 0, padding.bottom);
454 455
          } else {
            headerPadding = EdgeInsets.fromLTRB(padding.left, padding.top, 0, padding.bottom);
456 457
            listPadding = EdgeInsets.fromLTRB(widget.header != null ? 0 : padding.left, padding.top, widget.footer != null ? 0 : padding.right, padding.bottom);
            footerPadding = EdgeInsets.fromLTRB(0, padding.top, padding.right, padding.bottom);
458 459 460 461 462
          }
          break;
        case Axis.vertical:
          if (widget.reverse) {
            headerPadding = EdgeInsets.fromLTRB(padding.left, 0, padding.right, padding.bottom);
463 464
            listPadding = EdgeInsets.fromLTRB(padding.left, widget.footer != null ? 0 : padding.top, padding.right, widget.header != null ? 0 : padding.bottom);
            footerPadding = EdgeInsets.fromLTRB(padding.left, padding.top, padding.right, 0);
465 466
          } else {
            headerPadding = EdgeInsets.fromLTRB(padding.left, padding.top, padding.right, 0);
467 468
            listPadding = EdgeInsets.fromLTRB(padding.left, widget.header != null ? 0 : padding.top, padding.right, widget.footer != null ? 0 : padding.bottom);
            footerPadding = EdgeInsets.fromLTRB(padding.left, 0, padding.right, padding.bottom);
469
          }
470
         break;
471
      }
472
    }
473

474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
    return CustomScrollView(
      scrollDirection: widget.scrollDirection,
      reverse: widget.reverse,
      controller: widget.scrollController,
      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>[
        if (widget.header != null)
489
          SliverPadding(
490
            padding: headerPadding,
491
            sliver: SliverToBoxAdapter(child: widget.header),
492
          ),
493 494 495 496
        SliverPadding(
          padding: listPadding,
          sliver: SliverReorderableList(
            itemBuilder: _itemBuilder,
497
            itemExtent: widget.itemExtent,
498
            prototypeItem: widget.prototypeItem,
499 500
            itemCount: widget.itemCount,
            onReorder: widget.onReorder,
501 502
            onReorderStart: widget.onReorderStart,
            onReorderEnd: widget.onReorderEnd,
503 504 505
            proxyDecorator: widget.proxyDecorator ?? _proxyDecorator,
          ),
        ),
506 507 508 509 510
        if (widget.footer != null)
          SliverPadding(
            padding: footerPadding,
            sliver: SliverToBoxAdapter(child: widget.footer),
          ),
511
      ],
512
    );
513 514
  }
}
515 516 517 518 519 520 521 522 523 524 525

// A global key that takes its identity from the object and uses a value of a
// particular type to identify itself.
//
// The difference with GlobalObjectKey is that it uses [==] instead of [identical]
// of the objects used to generate widgets.
@optionalTypeArgs
class _ReorderableListViewChildGlobalKey extends GlobalObjectKey {
  const _ReorderableListViewChildGlobalKey(this.subKey, this.state) : super(subKey);

  final Key subKey;
526
  final State state;
527 528 529 530 531 532 533 534 535 536 537

  @override
  bool operator ==(Object other) {
    if (other.runtimeType != runtimeType)
      return false;
    return other is _ReorderableListViewChildGlobalKey
        && other.subKey == subKey
        && other.state == state;
  }

  @override
538
  int get hashCode => Object.hash(subKey, state);
539
}