reorderable_list.dart 18 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 19 20 21 22 23

/// A list whose items the user can interactively reorder by dragging.
///
/// This class is appropriate for views 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.
///
24
/// All list items must have a key.
25 26
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=3fB1mxOsqJE}
27 28 29 30 31
///
/// 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.
///
32
/// {@tool dartpad}
33
///
34
/// ** See code in examples/api/lib/material/reorderable_list/reorderable_list_view.0.dart **
35 36 37 38 39 40 41 42 43 44 45 46
/// {@end-tool}
///
/// This example demonstrates using the [proxyDecorator] callback to customize the appearance of
/// a list item while it's being dragged.
/// {@tool snippet}
///
/// 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.
///
/// ** See code in examples/api/lib/material/reorderable_list/reorderable_list_view.1.dart **
/// {@end-tool}
47
class ReorderableListView extends StatefulWidget {
48 49 50 51 52 53
  /// Creates a reorderable list from a pre-built list of widgets.
  ///
  /// See also:
  ///
  ///   * [ReorderableListView.builder], which allows you to build a reorderable
  ///     list where the items are built as needed when scrolling the list.
54
  ReorderableListView({
55
    Key? key,
56
    required List<Widget> children,
57
    required this.onReorder,
58
    this.itemExtent,
59
    this.prototypeItem,
60 61
    this.proxyDecorator,
    this.buildDefaultDragHandles = true,
62
    this.padding,
63 64
    this.header,
    this.scrollDirection = Axis.vertical,
65
    this.reverse = false,
66 67 68 69 70 71 72 73 74 75
    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,
76 77 78
  }) : assert(scrollDirection != null),
       assert(onReorder != null),
       assert(children != null),
79 80 81 82
       assert(
         itemExtent == null || prototypeItem == null,
         'You can only pass itemExtent or prototypeItem, not both',
       ),
83 84 85
       assert(
         children.every((Widget w) => w.key != null),
         'All children of this widget must have a key.',
86
       ),
87
       assert(buildDefaultDragHandles != null),
88 89
       itemBuilder = ((BuildContext context, int index) => children[index]),
       itemCount = children.length,
90
       super(key: key);
91

92
  /// Creates a reorderable list from widget items that are created on demand.
93
  ///
94 95 96
  /// 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.
97
  ///
98 99
  /// The `itemBuilder` callback will be called only with indices greater than
  /// or equal to zero and less than `itemCount`.
100
  ///
101 102 103 104 105 106 107
  /// 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.
108
  ///
109 110 111
  /// This example creates a list using the
  /// [ReorderableListView.builder] constructor. Using the [IndexedWidgetBuilder], The
  /// list items are built lazily on demand.
112
  /// {@tool dartpad}
113 114
  ///
  ///
115
  /// ** See code in examples/api/lib/material/reorderable_list/reorderable_list_view.reorderable_list_view_builder.0.dart **
116
  /// {@end-tool}
117
  /// See also:
118
  ///
119 120 121 122 123 124 125
  ///   * [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,
126
    this.itemExtent,
127
    this.prototypeItem,
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
    this.proxyDecorator,
    this.buildDefaultDragHandles = true,
    this.padding,
    this.header,
    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),
147 148 149 150
       assert(
         itemExtent == null || prototypeItem == null,
         'You can only pass itemExtent or prototypeItem, not both',
       ),
151 152
       assert(buildDefaultDragHandles != null),
       super(key: key);
153

154 155 156 157 158 159 160
  /// {@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
161
  final ReorderCallback onReorder;
162

163 164 165
  /// {@macro flutter.widgets.reorderable_list.proxyDecorator}
  final ReorderItemProxyDecorator? proxyDecorator;

166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
  /// 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.
  ///
184
  /// {@tool dartpad}
185 186
  ///
  ///
187
  /// ** See code in examples/api/lib/material/reorderable_list/reorderable_list_view.build_default_drag_handles.0.dart **
188 189 190
  ///{@end-tool}
  final bool buildDefaultDragHandles;

191 192 193 194
  /// {@macro flutter.widgets.reorderable_list.padding}
  final EdgeInsets? padding;

  /// A non-reorderable header item to show before the items of the list.
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
  /// If null, no header will appear before the list.
  final Widget? header;

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

242 243 244
  /// {@macro flutter.widgets.list_view.itemExtent}
  final double? itemExtent;

245 246 247
  /// {@macro flutter.widgets.list_view.prototypeItem}
  final Widget? prototypeItem;

248
  @override
249
  State<ReorderableListView> createState() => _ReorderableListViewState();
250 251 252
}

class _ReorderableListViewState extends State<ReorderableListView> {
253 254 255 256
  Widget _wrapWithSemantics(Widget child, int index) {
    void reorder(int startIndex, int endIndex) {
      if (startIndex != endIndex)
        widget.onReorder(startIndex, endIndex);
257 258
    }

259 260 261 262 263
    // First, determine which semantics actions apply.
    final Map<CustomSemanticsAction, VoidCallback> semanticsActions = <CustomSemanticsAction, VoidCallback>{};

    // Create the appropriate semantics actions.
    void moveToStart() => reorder(index, 0);
264
    void moveToEnd() => reorder(index, widget.itemCount);
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
    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;
280
      }
281
      semanticsActions[CustomSemanticsAction(label: reorderItemBefore)] = moveBefore;
282 283
    }

284
    // If the item can move to after its current position in the list.
285
    if (index < widget.itemCount - 1) {
286 287 288 289 290 291 292 293
      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;
294 295
    }

296 297 298 299 300 301 302 303 304 305 306
    // 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,
      ),
307 308 309
    );
  }

310
  Widget _itemBuilder(BuildContext context, int index) {
311
    final Widget item = widget.itemBuilder(context, index);
312 313 314
    assert(() {
      if (item.key == null) {
        throw FlutterError(
315
          'Every item of ReorderableListView must have a key.',
316 317 318 319
        );
      }
      return true;
    }());
320 321 322 323 324 325 326 327 328 329 330

    // 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:
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
          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),
                      ),
                    ),
349
                  ),
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
                ],
              );
            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),
                      ),
                    ),
                  ),
                ],
              );
          }
373

374 375
        case TargetPlatform.iOS:
        case TargetPlatform.android:
376
        case TargetPlatform.fuchsia:
377 378 379 380 381
          return ReorderableDelayedDragStartListener(
            key: itemGlobalKey,
            index: index,
            child: itemWithSemantics,
          );
382 383 384
      }
    }

385 386 387 388 389
    return KeyedSubtree(
      key: itemGlobalKey,
      child: itemWithSemantics,
    );
  }
390

391 392 393 394 395 396 397 398
  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,
399
          child: child,
400 401 402 403
        );
      },
      child: child,
    );
404 405 406 407
  }

  @override
  Widget build(BuildContext context) {
408 409 410
    assert(debugCheckHasMaterialLocalizations(context));
    assert(debugCheckHasOverlay(context));

411
    // If there is a header we can't just apply the padding to the list,
412
    // so we break it up into padding for the header and padding for the list.
413
    final EdgeInsets padding = widget.padding ?? EdgeInsets.zero;
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
    late final EdgeInsets headerPadding;
    late final EdgeInsets listPadding;

    if (widget.header == null) {
      headerPadding = EdgeInsets.zero;
      listPadding = padding;
    } else {
      switch (widget.scrollDirection) {
        case Axis.horizontal:
          if (widget.reverse) {
            // Header on the right
            headerPadding = EdgeInsets.fromLTRB(0, padding.top, padding.right, padding.bottom);
            listPadding = EdgeInsets.fromLTRB(padding.left, padding.top, 0, padding.bottom);
          } else {
            // Header on the left
            headerPadding = EdgeInsets.fromLTRB(padding.left, padding.top, 0, padding.bottom);
            listPadding = EdgeInsets.fromLTRB(0, padding.top, padding.right, padding.bottom);
          }
          break;
        case Axis.vertical:
          if (widget.reverse) {
            // Header on the bottom
            headerPadding = EdgeInsets.fromLTRB(padding.left, 0, padding.right, padding.bottom);
            listPadding = EdgeInsets.fromLTRB(padding.left, padding.top, padding.right, 0);
          } else {
            // Header on the top
            headerPadding = EdgeInsets.fromLTRB(padding.left, padding.top, padding.right, 0);
            listPadding = EdgeInsets.fromLTRB(padding.left, 0, padding.right, padding.bottom);
          }
          break;
      }
445
    }
446

447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
    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)
462
          SliverPadding(
463
            padding: headerPadding,
464
            sliver: SliverToBoxAdapter(child: widget.header),
465
          ),
466 467 468 469
        SliverPadding(
          padding: listPadding,
          sliver: SliverReorderableList(
            itemBuilder: _itemBuilder,
470
            itemExtent: widget.itemExtent,
471
            prototypeItem: widget.prototypeItem,
472 473 474 475 476 477
            itemCount: widget.itemCount,
            onReorder: widget.onReorder,
            proxyDecorator: widget.proxyDecorator ?? _proxyDecorator,
          ),
        ),
      ],
478
    );
479 480
  }
}
481 482 483 484 485 486 487 488 489 490 491

// 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;
492
  final State state;
493 494 495 496 497 498 499 500 501 502 503 504 505

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

  @override
  int get hashCode => hashValues(subKey, state);
}