expansion_panel.dart 17.8 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 15 16
import 'mergeable_material.dart';
import 'theme.dart';

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

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

  final S salt;
  final V value;

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

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

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

48 49 50 51 52
/// 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].
53
typedef ExpansionPanelCallback = void Function(int panelIndex, bool isExpanded);
54 55 56

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

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

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

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

105 106 107
}

/// An expansion panel that allows for radio-like functionality.
108 109
/// This means that at any given time, at most, one [ExpansionPanelRadio]
/// can remain expanded.
110 111
///
/// A unique identifier [value] must be assigned to each panel.
112 113 114 115
/// This identifier allows the [ExpansionPanelList] to determine
/// which [ExpansionPanelRadio] instance should be expanded.
///
/// See [ExpansionPanelList.radio] for a sample implementation.
116 117 118 119 120 121 122 123 124 125
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,
126
    bool canTapOnHeader = false,
127
  }) : assert(value != null),
128 129 130 131 132
      super(
        body: body,
        headerBuilder: headerBuilder,
        canTapOnHeader: canTapOnHeader,
      );
133 134 135 136

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

139
/// A material expansion panel list that lays out its children and animates
140 141
/// expansions.
///
142 143 144
/// Note that [expansionCallback] behaves differently for [ExpansionPanelList]
/// and [ExpansionPanelList.radio].
///
145
/// {@tool dartpad --template=stateful_widget_scaffold}
146 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
///
/// 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}
///
217 218 219
/// See also:
///
///  * [ExpansionPanel]
220
///  * [ExpansionPanelList.radio]
221
///  * <https://material.io/design/components/lists.html#types>
222
class ExpansionPanelList extends StatefulWidget {
223 224
  /// Creates an expansion panel list widget. The [expansionCallback] is
  /// triggered when an expansion panel expand/collapse button is pushed.
225 226
  ///
  /// The [children] and [animationDuration] arguments must not be null.
227
  const ExpansionPanelList({
228
    Key key,
229
    this.children = const <ExpansionPanel>[],
230
    this.expansionCallback,
231
    this.animationDuration = kThemeAnimationDuration,
232
    this.expandedHeaderPadding = _kPanelHeaderExpandedDefaultPadding,
233
    this.dividerColor,
234 235
  }) : assert(children != null),
       assert(animationDuration != null),
236
       _allowOnlyOnePanelOpen = false,
237
       initialOpenPanelValue = null,
238 239 240 241 242 243 244 245 246
       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].
247
  ///
248
  /// {@tool dartpad --template=stateful_widget_scaffold}
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 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
  ///
  /// 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}
316 317
  const ExpansionPanelList.radio({
    Key key,
318
    this.children = const <ExpansionPanelRadio>[],
319 320 321
    this.expansionCallback,
    this.animationDuration = kThemeAnimationDuration,
    this.initialOpenPanelValue,
322
    this.expandedHeaderPadding = _kPanelHeaderExpandedDefaultPadding,
323
    this.dividerColor,
324
  }) : assert(children != null),
325 326
       assert(animationDuration != null),
       _allowOnlyOnePanelOpen = true,
327
       super(key: key);
328

329
  /// The children of the expansion panel list. They are laid out in a similar
330
  /// fashion to [ListBody].
331 332 333 334
  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
335 336 337 338 339 340 341 342 343 344 345
  /// 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.
346 347 348 349 350 351 352 353
  ///
  /// 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;

354 355 356 357 358 359 360 361
  // 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;

362 363 364 365 366 367
  /// 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;

368 369 370 371 372 373
  /// 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;

374
  @override
375
  State<StatefulWidget> createState() => _ExpansionPanelListState();
376 377 378 379 380 381 382 383 384
}

class _ExpansionPanelListState extends State<ExpansionPanelList> {
  ExpansionPanelRadio _currentOpenPanel;

  @override
  void initState() {
    super.initState();
    if (widget._allowOnlyOnePanelOpen) {
385 386
      assert(_allIdentifiersUnique(), 'All ExpansionPanelRadio identifier values must be unique.');
      if (widget.initialOpenPanelValue != null) {
387 388
        _currentOpenPanel =
          searchPanelByValue(widget.children.cast<ExpansionPanelRadio>(), widget.initialOpenPanelValue);
389 390 391 392 393 394 395
      }
    }
  }

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

397
    if (widget._allowOnlyOnePanelOpen) {
398 399 400 401
      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) {
402 403
        _currentOpenPanel =
          searchPanelByValue(widget.children.cast<ExpansionPanelRadio>(), widget.initialOpenPanelValue);
404
      }
405
    } else {
406 407 408 409 410 411
      _currentOpenPanel = null;
    }
  }

  bool _allIdentifiersUnique() {
    final Map<Object, bool> identifierMap = <Object, bool>{};
412
    for (final ExpansionPanelRadio child in widget.children.cast<ExpansionPanelRadio>()) {
413 414 415 416 417
      identifierMap[child.value] = true;
    }
    return identifierMap.length == widget.children.length;
  }

418
  bool _isChildExpanded(int index) {
419
    if (widget._allowOnlyOnePanelOpen) {
420
      final ExpansionPanelRadio radioWidget = widget.children[index] as ExpansionPanelRadio;
421 422 423 424 425 426 427 428 429 430
      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) {
431
      final ExpansionPanelRadio pressedChild = widget.children[index] as ExpansionPanelRadio;
432

433 434
      // If another ExpansionPanelRadio was already open, apply its
      // expansionCallback (if any) to false, because it's closing.
435
      for (int childIndex = 0; childIndex < widget.children.length; childIndex += 1) {
436
        final ExpansionPanelRadio child = widget.children[childIndex] as ExpansionPanelRadio;
437 438 439 440 441
        if (widget.expansionCallback != null &&
            childIndex != index &&
            child.value == _currentOpenPanel?.value)
          widget.expansionCallback(childIndex, false);
      }
442 443 444 445 446 447 448 449

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

  ExpansionPanelRadio searchPanelByValue(List<ExpansionPanelRadio> panels, Object value)  {
450
    for (final ExpansionPanelRadio panel in panels) {
451 452
      if (panel.value == value)
        return panel;
453
    }
454
    return null;
455 456 457 458 459 460
  }

  @override
  Widget build(BuildContext context) {
    final List<MergeableMaterialItem> items = <MergeableMaterialItem>[];

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

465
      final ExpansionPanel child = widget.children[index];
466 467 468 469
      final Widget headerWidget = child.headerBuilder(
        context,
        _isChildExpanded(index),
      );
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485

      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,
486
          child: expandIconContainer,
487 488 489
        );
      }
      Widget header = Row(
490
        children: <Widget>[
491 492
          Expanded(
            child: AnimatedContainer(
493
              duration: widget.animationDuration,
494
              curve: Curves.fastOutSlowIn,
495
              margin: _isChildExpanded(index) ? widget.expandedHeaderPadding : EdgeInsets.zero,
496
              child: ConstrainedBox(
497
                constraints: const BoxConstraints(minHeight: _kPanelHeaderCollapsedHeight),
498
                child: headerWidget,
499 500
              ),
            ),
501
          ),
502
          expandIconContainer,
503
        ],
504
      );
505 506 507 508 509
      if (child.canTapOnHeader) {
        header = MergeSemantics(
          child: InkWell(
            onTap: () => _handlePressed(_isChildExpanded(index), index),
            child: header,
510
          ),
511 512
        );
      }
513
      items.add(
514 515 516
        MaterialSlice(
          key: _SaltedKey<BuildContext, int>(context, index * 2),
          child: Column(
517
            children: <Widget>[
518
              header,
519 520
              AnimatedCrossFade(
                firstChild: Container(height: 0.0),
521
                secondChild: child.body,
522 523
                firstCurve: const Interval(0.0, 0.6, curve: Curves.fastOutSlowIn),
                secondCurve: const Interval(0.4, 1.0, curve: Curves.fastOutSlowIn),
524
                sizeCurve: Curves.fastOutSlowIn,
525
                crossFadeState: _isChildExpanded(index) ? CrossFadeState.showSecond : CrossFadeState.showFirst,
526
                duration: widget.animationDuration,
527 528 529 530
              ),
            ],
          ),
        ),
531 532
      );

533
      if (_isChildExpanded(index) && index != widget.children.length - 1)
534
        items.add(MaterialGap(key: _SaltedKey<BuildContext, int>(context, index * 2 + 1)));
535 536
    }

537
    return MergeableMaterial(
538
      hasDividers: true,
539
      dividerColor: widget.dividerColor,
540
      children: items,
541 542 543
    );
  }
}