expansion_panel.dart 18.4 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 6
// @dart = 2.8

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

10
import 'constants.dart';
11
import 'expand_icon.dart';
12
import 'ink_well.dart';
13
import 'material_localizations.dart';
14
import 'mergeable_material.dart';
15
import 'shadows.dart';
16 17
import 'theme.dart';

18
const double _kPanelHeaderCollapsedHeight = kMinInteractiveDimension;
19 20 21
const EdgeInsets _kPanelHeaderExpandedDefaultPadding = EdgeInsets.symmetric(
    vertical: 64.0 - _kPanelHeaderCollapsedHeight
);
22

23 24 25 26 27 28 29
class _SaltedKey<S, V> extends LocalKey {
  const _SaltedKey(this.salt, this.value);

  final S salt;
  final V value;

  @override
30
  bool operator ==(Object other) {
31 32
    if (other.runtimeType != runtimeType)
      return false;
33 34 35
    return other is _SaltedKey<S, V>
        && other.salt == salt
        && other.value == value;
36 37 38 39 40 41 42
  }

  @override
  int get hashCode => hashValues(runtimeType, salt, value);

  @override
  String toString() {
43 44
    final String saltString = S == String ? "<'$salt'>" : '<$salt>';
    final String valueString = V == String ? "<'$value'>" : '<$value>';
45 46 47 48
    return '[$saltString $valueString]';
  }
}

49 50 51 52 53
/// Signature for the callback that's called when an [ExpansionPanel] is
/// expanded or collapsed.
///
/// The position of the panel within an [ExpansionPanelList] is given by
/// [panelIndex].
54
typedef ExpansionPanelCallback = void Function(int panelIndex, bool isExpanded);
55 56 57

/// Signature for the callback that's called when the header of the
/// [ExpansionPanel] needs to rebuild.
58
typedef ExpansionPanelHeaderBuilder = Widget Function(BuildContext context, bool isExpanded);
59

60
/// A material expansion panel. It has a header and a body and can be either
61 62 63 64 65 66
/// expanded or collapsed. The body of the panel is only visible when it is
/// expanded.
///
/// Expansion panels are only intended to be used as children for
/// [ExpansionPanelList].
///
67 68
/// See [ExpansionPanelList] for a sample implementation.
///
69 70 71
/// See also:
///
///  * [ExpansionPanelList]
72
///  * <https://material.io/design/components/lists.html#types>
73 74
class ExpansionPanel {
  /// Creates an expansion panel to be used as a child for [ExpansionPanelList].
75
  /// See [ExpansionPanelList] for an example on how to use this widget.
76
  ///
77
  /// The [headerBuilder], [body], and [isExpanded] arguments must not be null.
78 79 80
  ExpansionPanel({
    @required this.headerBuilder,
    @required this.body,
81
    this.isExpanded = false,
82
    this.canTapOnHeader = false,
83 84
  }) : assert(headerBuilder != null),
       assert(body != null),
85 86
       assert(isExpanded != null),
       assert(canTapOnHeader != null);
87 88 89 90 91 92 93 94 95 96 97 98 99

  /// The widget builder that builds the expansion panels' header.
  final ExpansionPanelHeaderBuilder headerBuilder;

  /// The body of the expansion panel that's displayed below the header.
  ///
  /// This widget is visible only when the panel is expanded.
  final Widget body;

  /// Whether the panel is expanded.
  ///
  /// Defaults to false.
  final bool isExpanded;
100

101 102 103 104 105
  /// Whether tapping on the panel's header will expand/collapse it.
  ///
  /// Defaults to false.
  final bool canTapOnHeader;

106 107 108
}

/// An expansion panel that allows for radio-like functionality.
109 110
/// This means that at any given time, at most, one [ExpansionPanelRadio]
/// can remain expanded.
111 112
///
/// A unique identifier [value] must be assigned to each panel.
113 114 115 116
/// This identifier allows the [ExpansionPanelList] to determine
/// which [ExpansionPanelRadio] instance should be expanded.
///
/// See [ExpansionPanelList.radio] for a sample implementation.
117 118 119 120 121 122 123 124 125 126
class ExpansionPanelRadio extends ExpansionPanel {

  /// An expansion panel that allows for radio functionality.
  ///
  /// A unique [value] must be passed into the constructor. The
  /// [headerBuilder], [body], [value] must not be null.
  ExpansionPanelRadio({
    @required this.value,
    @required ExpansionPanelHeaderBuilder headerBuilder,
    @required Widget body,
127
    bool canTapOnHeader = false,
128
  }) : assert(value != null),
129 130 131 132 133
      super(
        body: body,
        headerBuilder: headerBuilder,
        canTapOnHeader: canTapOnHeader,
      );
134 135 136 137

  /// The value that uniquely identifies a radio panel so that the currently
  /// selected radio panel can be identified.
  final Object value;
138 139
}

140
/// A material expansion panel list that lays out its children and animates
141 142
/// expansions.
///
143 144 145
/// Note that [expansionCallback] behaves differently for [ExpansionPanelList]
/// and [ExpansionPanelList.radio].
///
146
/// {@tool dartpad --template=stateful_widget_scaffold}
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
///
/// Here is a simple example of how to implement ExpansionPanelList.
///
/// ```dart preamble
/// // stores ExpansionPanel state information
/// class Item {
///   Item({
///     this.expandedValue,
///     this.headerValue,
///     this.isExpanded = false,
///   });
///
///   String expandedValue;
///   String headerValue;
///   bool isExpanded;
/// }
///
/// List<Item> generateItems(int numberOfItems) {
///   return List.generate(numberOfItems, (int index) {
///     return Item(
///       headerValue: 'Panel $index',
///       expandedValue: 'This is item number $index',
///     );
///   });
/// }
/// ```
///
/// ```dart
/// List<Item> _data = generateItems(8);
///
/// @override
/// Widget build(BuildContext context) {
///   return SingleChildScrollView(
///     child: Container(
///       child: _buildPanel(),
///     ),
///   );
/// }
///
/// Widget _buildPanel() {
///   return ExpansionPanelList(
///     expansionCallback: (int index, bool isExpanded) {
///       setState(() {
///         _data[index].isExpanded = !isExpanded;
///       });
///     },
///     children: _data.map<ExpansionPanel>((Item item) {
///       return ExpansionPanel(
///         headerBuilder: (BuildContext context, bool isExpanded) {
///           return ListTile(
///             title: Text(item.headerValue),
///           );
///         },
///         body: ListTile(
///           title: Text(item.expandedValue),
///           subtitle: Text('To delete this panel, tap the trash can icon'),
///           trailing: Icon(Icons.delete),
///           onTap: () {
///             setState(() {
///               _data.removeWhere((currentItem) => item == currentItem);
///             });
///           }
///         ),
///         isExpanded: item.isExpanded,
///       );
///     }).toList(),
///   );
/// }
/// ```
/// {@end-tool}
///
218 219 220
/// See also:
///
///  * [ExpansionPanel]
221
///  * [ExpansionPanelList.radio]
222
///  * <https://material.io/design/components/lists.html#types>
223
class ExpansionPanelList extends StatefulWidget {
224 225
  /// Creates an expansion panel list widget. The [expansionCallback] is
  /// triggered when an expansion panel expand/collapse button is pushed.
226 227
  ///
  /// The [children] and [animationDuration] arguments must not be null.
228
  const ExpansionPanelList({
229
    Key key,
230
    this.children = const <ExpansionPanel>[],
231
    this.expansionCallback,
232
    this.animationDuration = kThemeAnimationDuration,
233
    this.expandedHeaderPadding = _kPanelHeaderExpandedDefaultPadding,
234
    this.dividerColor,
235
    this.elevation = 2,
236 237
  }) : assert(children != null),
       assert(animationDuration != null),
238
       _allowOnlyOnePanelOpen = false,
239
       initialOpenPanelValue = null,
240 241 242 243 244 245 246 247 248
       super(key: key);

  /// Creates a radio expansion panel list widget.
  ///
  /// This widget allows for at most one panel in the list to be open.
  /// The expansion panel callback is triggered when an expansion panel
  /// expand/collapse button is pushed. The [children] and [animationDuration]
  /// arguments must not be null. The [children] objects must be instances
  /// of [ExpansionPanelRadio].
249
  ///
250
  /// {@tool dartpad --template=stateful_widget_scaffold}
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
  ///
  /// Here is a simple example of how to implement ExpansionPanelList.radio.
  ///
  /// ```dart preamble
  /// // stores ExpansionPanel state information
  /// class Item {
  ///   Item({
  ///     this.id,
  ///     this.expandedValue,
  ///     this.headerValue,
  ///   });
  ///
  ///   int id;
  ///   String expandedValue;
  ///   String headerValue;
  /// }
  ///
  /// List<Item> generateItems(int numberOfItems) {
  ///   return List.generate(numberOfItems, (int index) {
  ///     return Item(
  ///       id: index,
  ///       headerValue: 'Panel $index',
  ///       expandedValue: 'This is item number $index',
  ///     );
  ///   });
  /// }
  /// ```
  ///
  /// ```dart
  /// List<Item> _data = generateItems(8);
  ///
  /// @override
  /// Widget build(BuildContext context) {
  ///   return SingleChildScrollView(
  ///     child: Container(
  ///       child: _buildPanel(),
  ///     ),
  ///   );
  /// }
  ///
  /// Widget _buildPanel() {
  ///   return ExpansionPanelList.radio(
  ///     initialOpenPanelValue: 2,
  ///     children: _data.map<ExpansionPanelRadio>((Item item) {
  ///       return ExpansionPanelRadio(
  ///         value: item.id,
  ///         headerBuilder: (BuildContext context, bool isExpanded) {
  ///           return ListTile(
  ///             title: Text(item.headerValue),
  ///           );
  ///         },
  ///         body: ListTile(
  ///           title: Text(item.expandedValue),
  ///           subtitle: Text('To delete this panel, tap the trash can icon'),
  ///           trailing: Icon(Icons.delete),
  ///           onTap: () {
  ///             setState(() {
  ///               _data.removeWhere((currentItem) => item == currentItem);
  ///             });
  ///           }
  ///         )
  ///       );
  ///     }).toList(),
  ///   );
  /// }
  /// ```
  /// {@end-tool}
318 319
  const ExpansionPanelList.radio({
    Key key,
320
    this.children = const <ExpansionPanelRadio>[],
321 322 323
    this.expansionCallback,
    this.animationDuration = kThemeAnimationDuration,
    this.initialOpenPanelValue,
324
    this.expandedHeaderPadding = _kPanelHeaderExpandedDefaultPadding,
325
    this.dividerColor,
326
    this.elevation = 2,
327
  }) : assert(children != null),
328 329
       assert(animationDuration != null),
       _allowOnlyOnePanelOpen = true,
330
       super(key: key);
331

332
  /// The children of the expansion panel list. They are laid out in a similar
333
  /// fashion to [ListBody].
334 335 336 337
  final List<ExpansionPanel> children;

  /// The callback that gets called whenever one of the expand/collapse buttons
  /// is pressed. The arguments passed to the callback are the index of the
338 339 340 341 342 343 344 345 346 347 348
  /// pressed panel and whether the panel is currently expanded or not.
  ///
  /// If ExpansionPanelList.radio is used, the callback may be called a
  /// second time if a different panel was previously open. The arguments
  /// passed to the second callback are the index of the panel that will close
  /// and false, marking that it will be closed.
  ///
  /// For ExpansionPanelList, the callback needs to setState when it's notified
  /// about the closing/opening panel. On the other hand, the callback for
  /// ExpansionPanelList.radio is simply meant to inform the parent widget of
  /// changes, as the radio panels' open/close states are managed internally.
349 350 351 352 353 354 355 356
  ///
  /// This callback is useful in order to keep track of the expanded/collapsed
  /// panels in a parent widget that may need to react to these changes.
  final ExpansionPanelCallback expansionCallback;

  /// The duration of the expansion animation.
  final Duration animationDuration;

357 358 359 360 361 362 363 364
  // Whether multiple panels can be open simultaneously
  final bool _allowOnlyOnePanelOpen;

  /// The value of the panel that initially begins open. (This value is
  /// only used when initializing with the [ExpansionPanelList.radio]
  /// constructor.)
  final Object initialOpenPanelValue;

365 366 367 368 369 370
  /// The padding that surrounds the panel header when expanded.
  ///
  /// By default, 16px of space is added to the header vertically (above and below)
  /// during expansion.
  final EdgeInsets expandedHeaderPadding;

371 372 373 374 375 376
  /// Defines color for the divider when [ExpansionPanel.isExpanded] is false.
  ///
  /// If `dividerColor` is null, then [DividerThemeData.color] is used. If that
  /// is null, then [ThemeData.dividerColor] is used.
  final Color dividerColor;

377 378 379 380 381 382 383 384 385 386 387
  /// Defines elevation for the [ExpansionPanel] while it's expanded.
  ///
  /// This uses [kElevationToShadow] to simulate shadows, it does not use
  /// [Material]'s arbitrary elevation feature.
  ///
  /// The following values can be used to define the elevation: 0, 1, 2, 3, 4, 6,
  /// 8, 9, 12, 16, 24.
  ///
  /// By default, the value of elevation is 2.
  final int elevation;

388
  @override
389
  State<StatefulWidget> createState() => _ExpansionPanelListState();
390 391 392 393 394 395 396 397 398
}

class _ExpansionPanelListState extends State<ExpansionPanelList> {
  ExpansionPanelRadio _currentOpenPanel;

  @override
  void initState() {
    super.initState();
    if (widget._allowOnlyOnePanelOpen) {
399 400
      assert(_allIdentifiersUnique(), 'All ExpansionPanelRadio identifier values must be unique.');
      if (widget.initialOpenPanelValue != null) {
401 402
        _currentOpenPanel =
          searchPanelByValue(widget.children.cast<ExpansionPanelRadio>(), widget.initialOpenPanelValue);
403 404 405 406 407 408 409
      }
    }
  }

  @override
  void didUpdateWidget(ExpansionPanelList oldWidget) {
    super.didUpdateWidget(oldWidget);
410

411
    if (widget._allowOnlyOnePanelOpen) {
412 413 414 415
      assert(_allIdentifiersUnique(), 'All ExpansionPanelRadio identifier values must be unique.');
      // If the previous widget was non-radio ExpansionPanelList, initialize the
      // open panel to widget.initialOpenPanelValue
      if (!oldWidget._allowOnlyOnePanelOpen) {
416 417
        _currentOpenPanel =
          searchPanelByValue(widget.children.cast<ExpansionPanelRadio>(), widget.initialOpenPanelValue);
418
      }
419
    } else {
420 421 422 423 424 425
      _currentOpenPanel = null;
    }
  }

  bool _allIdentifiersUnique() {
    final Map<Object, bool> identifierMap = <Object, bool>{};
426
    for (final ExpansionPanelRadio child in widget.children.cast<ExpansionPanelRadio>()) {
427 428 429 430 431
      identifierMap[child.value] = true;
    }
    return identifierMap.length == widget.children.length;
  }

432
  bool _isChildExpanded(int index) {
433
    if (widget._allowOnlyOnePanelOpen) {
434
      final ExpansionPanelRadio radioWidget = widget.children[index] as ExpansionPanelRadio;
435 436 437 438 439 440 441 442 443 444
      return _currentOpenPanel?.value == radioWidget.value;
    }
    return widget.children[index].isExpanded;
  }

  void _handlePressed(bool isExpanded, int index) {
    if (widget.expansionCallback != null)
      widget.expansionCallback(index, isExpanded);

    if (widget._allowOnlyOnePanelOpen) {
445
      final ExpansionPanelRadio pressedChild = widget.children[index] as ExpansionPanelRadio;
446

447 448
      // If another ExpansionPanelRadio was already open, apply its
      // expansionCallback (if any) to false, because it's closing.
449
      for (int childIndex = 0; childIndex < widget.children.length; childIndex += 1) {
450
        final ExpansionPanelRadio child = widget.children[childIndex] as ExpansionPanelRadio;
451 452 453 454 455
        if (widget.expansionCallback != null &&
            childIndex != index &&
            child.value == _currentOpenPanel?.value)
          widget.expansionCallback(childIndex, false);
      }
456 457 458 459 460 461 462 463

      setState(() {
        _currentOpenPanel = isExpanded ? null : pressedChild;
      });
    }
  }

  ExpansionPanelRadio searchPanelByValue(List<ExpansionPanelRadio> panels, Object value)  {
464
    for (final ExpansionPanelRadio panel in panels) {
465 466
      if (panel.value == value)
        return panel;
467
    }
468
    return null;
469 470 471 472
  }

  @override
  Widget build(BuildContext context) {
473 474 475 476 477
    assert(kElevationToShadow.containsKey(widget.elevation),
      'Invalid value for elevation. See the kElevationToShadow constant for'
      ' possible elevation values.'
    );

478 479
    final List<MergeableMaterialItem> items = <MergeableMaterialItem>[];

480
    for (int index = 0; index < widget.children.length; index += 1) {
481
      if (_isChildExpanded(index) && index != 0 && !_isChildExpanded(index - 1))
482
        items.add(MaterialGap(key: _SaltedKey<BuildContext, int>(context, index * 2 - 1)));
483

484
      final ExpansionPanel child = widget.children[index];
485 486 487 488
      final Widget headerWidget = child.headerBuilder(
        context,
        _isChildExpanded(index),
      );
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504

      Widget expandIconContainer = Container(
        margin: const EdgeInsetsDirectional.only(end: 8.0),
        child: ExpandIcon(
          isExpanded: _isChildExpanded(index),
          padding: const EdgeInsets.all(16.0),
          onPressed: !child.canTapOnHeader
              ? (bool isExpanded) => _handlePressed(isExpanded, index)
              : null,
        ),
      );
      if (!child.canTapOnHeader) {
        final MaterialLocalizations localizations = MaterialLocalizations.of(context);
        expandIconContainer = Semantics(
          label: _isChildExpanded(index)? localizations.expandedIconTapHint : localizations.collapsedIconTapHint,
          container: true,
505
          child: expandIconContainer,
506 507 508
        );
      }
      Widget header = Row(
509
        children: <Widget>[
510 511
          Expanded(
            child: AnimatedContainer(
512
              duration: widget.animationDuration,
513
              curve: Curves.fastOutSlowIn,
514
              margin: _isChildExpanded(index) ? widget.expandedHeaderPadding : EdgeInsets.zero,
515
              child: ConstrainedBox(
516
                constraints: const BoxConstraints(minHeight: _kPanelHeaderCollapsedHeight),
517
                child: headerWidget,
518 519
              ),
            ),
520
          ),
521
          expandIconContainer,
522
        ],
523
      );
524 525 526 527 528
      if (child.canTapOnHeader) {
        header = MergeSemantics(
          child: InkWell(
            onTap: () => _handlePressed(_isChildExpanded(index), index),
            child: header,
529
          ),
530 531
        );
      }
532
      items.add(
533 534 535
        MaterialSlice(
          key: _SaltedKey<BuildContext, int>(context, index * 2),
          child: Column(
536
            children: <Widget>[
537
              header,
538 539
              AnimatedCrossFade(
                firstChild: Container(height: 0.0),
540
                secondChild: child.body,
541 542
                firstCurve: const Interval(0.0, 0.6, curve: Curves.fastOutSlowIn),
                secondCurve: const Interval(0.4, 1.0, curve: Curves.fastOutSlowIn),
543
                sizeCurve: Curves.fastOutSlowIn,
544
                crossFadeState: _isChildExpanded(index) ? CrossFadeState.showSecond : CrossFadeState.showFirst,
545
                duration: widget.animationDuration,
546 547 548 549
              ),
            ],
          ),
        ),
550 551
      );

552
      if (_isChildExpanded(index) && index != widget.children.length - 1)
553
        items.add(MaterialGap(key: _SaltedKey<BuildContext, int>(context, index * 2 + 1)));
554 555
    }

556
    return MergeableMaterial(
557
      hasDividers: true,
558
      dividerColor: widget.dividerColor,
559
      elevation: widget.elevation,
560
      children: items,
561 562 563
    );
  }
}