reorderable_list.dart 18.3 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 'theme.dart';
15 16 17

/// A list whose items the user can interactively reorder by dragging.
///
18
/// {@youtube 560 315 https://www.youtube.com/watch?v=3fB1mxOsqJE}
19 20 21 22 23
///
/// 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.
///
24
/// {@tool dartpad}
25
///
26
/// ** See code in examples/api/lib/material/reorderable_list/reorderable_list_view.0.dart **
27 28
/// {@end-tool}
///
29 30 31 32 33 34 35 36 37
/// 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.
///
38 39
/// This example demonstrates using the [ReorderableListView.proxyDecorator] callback
/// to customize the appearance of a list item while it's being dragged.
40
///
41 42 43 44 45
/// {@tool dartpad}
/// While a drag is underway, the widget returned by the [ReorderableListView.proxyDecorator]
/// callback 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 [ReorderableListView.proxyDecorator]
/// callback in this example is similar to the default one except that it changes the
46
/// proxy item's background color.
47 48 49
///
/// ** See code in examples/api/lib/material/reorderable_list/reorderable_list_view.1.dart **
/// {@end-tool}
50 51 52 53 54 55 56 57 58 59 60
///
/// This example demonstrates using the [ReorderableListView.proxyDecorator] callback to
/// customize the appearance of a [Card] while it's being dragged.
///
/// {@tool dartpad}
/// The default [proxyDecorator] wraps the dragged item in a [Material] widget and animates
/// its elevation. This example demonstrates how to use the [ReorderableListView.proxyDecorator]
/// callback to update the dragged card elevation without inserted a new [Material] widget.
///
/// ** See code in examples/api/lib/material/reorderable_list/reorderable_list_view.2.dart **
/// {@end-tool}
61
class ReorderableListView extends StatefulWidget {
62 63
  /// Creates a reorderable list from a pre-built list of widgets.
  ///
64 65 66 67 68
  /// 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.
  ///
69 70 71 72
  /// See also:
  ///
  ///   * [ReorderableListView.builder], which allows you to build a reorderable
  ///     list where the items are built as needed when scrolling the list.
73
  ReorderableListView({
74
    super.key,
75
    required List<Widget> children,
76
    required this.onReorder,
77 78
    this.onReorderStart,
    this.onReorderEnd,
79
    this.itemExtent,
80
    this.itemExtentBuilder,
81
    this.prototypeItem,
82 83
    this.proxyDecorator,
    this.buildDefaultDragHandles = true,
84
    this.padding,
85
    this.header,
86
    this.footer,
87
    this.scrollDirection = Axis.vertical,
88
    this.reverse = false,
89 90 91 92 93 94 95 96 97 98
    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,
99
    this.autoScrollerVelocityScalar,
100
  }) : assert(
101 102 103 104
        (itemExtent == null && prototypeItem == null) ||
        (itemExtent == null && itemExtentBuilder == null) ||
        (prototypeItem == null && itemExtentBuilder == null),
        'You can only pass one of itemExtent, prototypeItem and itemExtentBuilder.',
105
       ),
106 107 108
       assert(
         children.every((Widget w) => w.key != null),
         'All children of this widget must have a key.',
109
       ),
110
       itemBuilder = ((BuildContext context, int index) => children[index]),
111
       itemCount = children.length;
112

113
  /// Creates a reorderable list from widget items that are created on demand.
114
  ///
115 116 117
  /// 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.
118
  ///
119 120
  /// The `itemBuilder` callback will be called only with indices greater than
  /// or equal to zero and less than `itemCount`.
121
  ///
122 123 124 125 126 127 128
  /// 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.
129
  ///
130 131 132
  /// This example creates a list using the
  /// [ReorderableListView.builder] constructor. Using the [IndexedWidgetBuilder], The
  /// list items are built lazily on demand.
133
  /// {@tool dartpad}
134
  ///
135
  /// ** See code in examples/api/lib/material/reorderable_list/reorderable_list_view.reorderable_list_view_builder.0.dart **
136
  /// {@end-tool}
137
  /// See also:
138
  ///
139 140 141
  ///   * [ReorderableListView], which allows you to build a reorderable
  ///     list with all the items passed into the constructor.
  const ReorderableListView.builder({
142
    super.key,
143 144 145
    required this.itemBuilder,
    required this.itemCount,
    required this.onReorder,
146 147
    this.onReorderStart,
    this.onReorderEnd,
148
    this.itemExtent,
149
    this.itemExtentBuilder,
150
    this.prototypeItem,
151 152 153 154
    this.proxyDecorator,
    this.buildDefaultDragHandles = true,
    this.padding,
    this.header,
155
    this.footer,
156 157 158 159 160 161 162 163 164 165 166 167
    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,
168
    this.autoScrollerVelocityScalar,
169
  }) : assert(itemCount >= 0),
170
       assert(
171 172 173 174
         (itemExtent == null && prototypeItem == null) ||
         (itemExtent == null && itemExtentBuilder == null) ||
         (prototypeItem == null && itemExtentBuilder == null),
         'You can only pass one of itemExtent, prototypeItem and itemExtentBuilder.',
175
       );
176

177 178 179 180 181 182 183
  /// {@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
184
  final ReorderCallback onReorder;
185

186 187 188 189 190 191
  /// {@macro flutter.widgets.reorderable_list.onReorderStart}
  final void Function(int index)? onReorderStart;

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

192 193 194
  /// {@macro flutter.widgets.reorderable_list.proxyDecorator}
  final ReorderItemProxyDecorator? proxyDecorator;

195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
  /// 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.
  ///
213
  /// {@tool dartpad}
214 215
  ///
  ///
216
  /// ** See code in examples/api/lib/material/reorderable_list/reorderable_list_view.build_default_drag_handles.0.dart **
217 218 219
  ///{@end-tool}
  final bool buildDefaultDragHandles;

220 221 222 223
  /// {@macro flutter.widgets.reorderable_list.padding}
  final EdgeInsets? padding;

  /// A non-reorderable header item to show before the items of the list.
224
  ///
225 226 227
  /// If null, no header will appear before the list.
  final Widget? header;

228 229 230 231 232
  /// 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;

233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
  /// {@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;
275

276 277 278
  /// {@macro flutter.widgets.list_view.itemExtent}
  final double? itemExtent;

279 280 281
  /// {@macro flutter.widgets.list_view.itemExtentBuilder}
  final ItemExtentBuilder? itemExtentBuilder;

282 283 284
  /// {@macro flutter.widgets.list_view.prototypeItem}
  final Widget? prototypeItem;

285
  /// {@macro flutter.widgets.EdgeDraggingAutoScroller.velocityScalar}
286 287
  ///
  /// {@macro flutter.widgets.SliverReorderableList.autoScrollerVelocityScalar.default}
288 289
  final double? autoScrollerVelocityScalar;

290
  @override
291
  State<ReorderableListView> createState() => _ReorderableListViewState();
292 293 294
}

class _ReorderableListViewState extends State<ReorderableListView> {
295
  Widget _itemBuilder(BuildContext context, int index) {
296
    final Widget item = widget.itemBuilder(context, index);
297 298 299
    assert(() {
      if (item.key == null) {
        throw FlutterError(
300
          'Every item of ReorderableListView must have a key.',
301 302 303 304
        );
      }
      return true;
    }());
305 306 307 308 309 310 311 312

    final Key itemGlobalKey = _ReorderableListViewChildGlobalKey(item.key!, this);

    if (widget.buildDefaultDragHandles) {
      switch (Theme.of(context).platform) {
        case TargetPlatform.linux:
        case TargetPlatform.windows:
        case TargetPlatform.macOS:
313 314 315 316 317
          switch (widget.scrollDirection) {
            case Axis.horizontal:
              return Stack(
                key: itemGlobalKey,
                children: <Widget>[
318
                  item,
319 320 321 322 323 324 325 326 327 328 329 330
                  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),
                      ),
                    ),
331
                  ),
332 333 334 335 336 337
                ],
              );
            case Axis.vertical:
              return Stack(
                key: itemGlobalKey,
                children: <Widget>[
338
                  item,
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
                  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),
                      ),
                    ),
                  ),
                ],
              );
          }
355

356 357
        case TargetPlatform.iOS:
        case TargetPlatform.android:
358
        case TargetPlatform.fuchsia:
359 360 361
          return ReorderableDelayedDragStartListener(
            key: itemGlobalKey,
            index: index,
362
            child: item,
363
          );
364 365 366
      }
    }

367 368
    return KeyedSubtree(
      key: itemGlobalKey,
369
      child: item,
370 371
    );
  }
372

373 374 375 376 377 378 379 380
  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,
381
          child: child,
382 383 384 385
        );
      },
      child: child,
    );
386 387 388 389
  }

  @override
  Widget build(BuildContext context) {
390 391 392
    assert(debugCheckHasMaterialLocalizations(context));
    assert(debugCheckHasOverlay(context));

393 394
    // 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.
395
    final EdgeInsets padding = widget.padding ?? EdgeInsets.zero;
396
    late final EdgeInsets headerPadding;
397
    late final EdgeInsets footerPadding;
398 399
    late final EdgeInsets listPadding;

400
    if (widget.header == null && widget.footer == null) {
401
      headerPadding = EdgeInsets.zero;
402
      footerPadding = EdgeInsets.zero;
403
      listPadding = padding;
404
    } else if (widget.header != null || widget.footer != null) {
405 406 407 408
      switch (widget.scrollDirection) {
        case Axis.horizontal:
          if (widget.reverse) {
            headerPadding = EdgeInsets.fromLTRB(0, padding.top, padding.right, padding.bottom);
409 410
            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);
411 412
          } else {
            headerPadding = EdgeInsets.fromLTRB(padding.left, padding.top, 0, padding.bottom);
413 414
            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);
415 416 417 418
          }
        case Axis.vertical:
          if (widget.reverse) {
            headerPadding = EdgeInsets.fromLTRB(padding.left, 0, padding.right, padding.bottom);
419 420
            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);
421 422
          } else {
            headerPadding = EdgeInsets.fromLTRB(padding.left, padding.top, padding.right, 0);
423 424
            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);
425 426
          }
      }
427
    }
428

429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
    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)
444
          SliverPadding(
445
            padding: headerPadding,
446
            sliver: SliverToBoxAdapter(child: widget.header),
447
          ),
448 449 450 451
        SliverPadding(
          padding: listPadding,
          sliver: SliverReorderableList(
            itemBuilder: _itemBuilder,
452
            itemExtent: widget.itemExtent,
453
            itemExtentBuilder: widget.itemExtentBuilder,
454
            prototypeItem: widget.prototypeItem,
455 456
            itemCount: widget.itemCount,
            onReorder: widget.onReorder,
457 458
            onReorderStart: widget.onReorderStart,
            onReorderEnd: widget.onReorderEnd,
459
            proxyDecorator: widget.proxyDecorator ?? _proxyDecorator,
460
            autoScrollerVelocityScalar: widget.autoScrollerVelocityScalar,
461 462
          ),
        ),
463 464 465 466 467
        if (widget.footer != null)
          SliverPadding(
            padding: footerPadding,
            sliver: SliverToBoxAdapter(child: widget.footer),
          ),
468
      ],
469
    );
470 471
  }
}
472 473 474 475 476 477 478 479 480 481 482

// 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;
483
  final State state;
484 485 486

  @override
  bool operator ==(Object other) {
487
    if (other.runtimeType != runtimeType) {
488
      return false;
489
    }
490 491 492 493 494 495
    return other is _ReorderableListViewChildGlobalKey
        && other.subKey == subKey
        && other.state == state;
  }

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