list_tile.dart 53.8 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
Adam Barth's avatar
Adam Barth committed
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
import 'dart:math' as math;

Adam Barth's avatar
Adam Barth committed
9
import 'package:flutter/widgets.dart';
10 11
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
Adam Barth's avatar
Adam Barth committed
12

13
import 'colors.dart';
14
import 'constants.dart';
15
import 'debug.dart';
16
import 'divider.dart';
Adam Barth's avatar
Adam Barth committed
17
import 'ink_well.dart';
18
import 'material_state.dart';
Hans Muller's avatar
Hans Muller committed
19
import 'theme.dart';
20
import 'theme_data.dart';
Adam Barth's avatar
Adam Barth committed
21

22 23
/// Defines the title font used for [ListTile] descendants of a [ListTileTheme].
///
24 25
/// List tiles that appear in a [Drawer] use the theme's [TextTheme.bodyText1]
/// text style, which is a little smaller than the theme's [TextTheme.subtitle1]
26 27
/// text style, which is used by default.
enum ListTileStyle {
Adam Barth's avatar
Adam Barth committed
28
  /// Use a title font that's appropriate for a [ListTile] in a list.
29 30
  list,

Adam Barth's avatar
Adam Barth committed
31
  /// Use a title font that's appropriate for a [ListTile] that appears in a [Drawer].
32
  drawer,
33 34
}

35
/// An inherited widget that defines color and style parameters for [ListTile]s
36 37 38 39 40 41 42
/// in this widget's subtree.
///
/// Values specified here are used for [ListTile] properties that are not given
/// an explicit non-null value.
///
/// The [Drawer] widget specifies a tile theme for its children which sets
/// [style] to [ListTileStyle.drawer].
43
class ListTileTheme extends InheritedTheme {
44 45
  /// Creates a list tile theme that controls the color and style parameters for
  /// [ListTile]s.
46 47
  const ListTileTheme({
    Key key,
48
    this.dense = false,
49
    this.shape,
50
    this.style = ListTileStyle.list,
51 52 53
    this.selectedColor,
    this.iconColor,
    this.textColor,
54
    this.contentPadding,
55 56
    this.tileColor,
    this.selectedTileColor,
57 58 59
    Widget child,
  }) : super(key: key, child: child);

60 61 62 63 64 65 66
  /// Creates a list tile theme that controls the color and style parameters for
  /// [ListTile]s, and merges in the current list tile theme, if any.
  ///
  /// The [child] argument must not be null.
  static Widget merge({
    Key key,
    bool dense,
67
    ShapeBorder shape,
68 69 70 71
    ListTileStyle style,
    Color selectedColor,
    Color iconColor,
    Color textColor,
72
    EdgeInsetsGeometry contentPadding,
73 74
    Color tileColor,
    Color selectedTileColor,
75 76 77
    @required Widget child,
  }) {
    assert(child != null);
78
    return Builder(
79 80
      builder: (BuildContext context) {
        final ListTileTheme parent = ListTileTheme.of(context);
81
        return ListTileTheme(
82 83
          key: key,
          dense: dense ?? parent.dense,
84
          shape: shape ?? parent.shape,
85 86 87 88
          style: style ?? parent.style,
          selectedColor: selectedColor ?? parent.selectedColor,
          iconColor: iconColor ?? parent.iconColor,
          textColor: textColor ?? parent.textColor,
89
          contentPadding: contentPadding ?? parent.contentPadding,
90 91
          tileColor: tileColor ?? parent.tileColor,
          selectedTileColor: selectedTileColor ?? parent.selectedTileColor,
92 93 94 95 96 97
          child: child,
        );
      },
    );
  }

98 99 100
  /// If true then [ListTile]s will have the vertically dense layout.
  final bool dense;

101 102 103
  /// If specified, [shape] defines the shape of the [ListTile]'s [InkWell] border.
  final ShapeBorder shape;

104 105 106 107 108 109 110 111 112 113 114 115
  /// If specified, [style] defines the font used for [ListTile] titles.
  final ListTileStyle style;

  /// If specified, the color used for icons and text when a [ListTile] is selected.
  final Color selectedColor;

  /// If specified, the icon color used for enabled [ListTile]s that are not selected.
  final Color iconColor;

  /// If specified, the text color used for enabled [ListTile]s that are not selected.
  final Color textColor;

116 117
  /// The tile's internal padding.
  ///
118 119
  /// Insets a [ListTile]'s contents: its [ListTile.leading], [ListTile.title],
  /// [ListTile.subtitle], and [ListTile.trailing] widgets.
120 121
  final EdgeInsetsGeometry contentPadding;

122 123 124 125 126 127 128 129 130 131 132 133
  /// If specified, defines the background color for `ListTile` when
  /// [ListTile.selected] is false.
  ///
  /// If [ListTile.tileColor] is provided, [tileColor] is ignored.
  final Color tileColor;

  /// If specified, defines the background color for `ListTile` when
  /// [ListTile.selected] is true.
  ///
  /// If [ListTile.selectedTileColor] is provided, [selectedTileColor] is ignored.
  final Color selectedTileColor;

134 135 136 137 138 139 140 141
  /// The closest instance of this class that encloses the given context.
  ///
  /// Typical usage is as follows:
  ///
  /// ```dart
  /// ListTileTheme theme = ListTileTheme.of(context);
  /// ```
  static ListTileTheme of(BuildContext context) {
142
    final ListTileTheme result = context.dependOnInheritedWidgetOfExactType<ListTileTheme>();
143
    return result ?? const ListTileTheme();
144 145
  }

146 147
  @override
  Widget wrap(BuildContext context, Widget child) {
148
    final ListTileTheme ancestorTheme = context.findAncestorWidgetOfExactType<ListTileTheme>();
149 150
    return identical(this, ancestorTheme) ? child : ListTileTheme(
      dense: dense,
151
      shape: shape,
152 153 154 155 156
      style: style,
      selectedColor: selectedColor,
      iconColor: iconColor,
      textColor: textColor,
      contentPadding: contentPadding,
157 158
      tileColor: tileColor,
      selectedTileColor: selectedTileColor,
159 160 161 162
      child: child,
    );
  }

163
  @override
164 165
  bool updateShouldNotify(ListTileTheme oldWidget) {
    return dense != oldWidget.dense
166
        || shape != oldWidget.shape
167 168 169
        || style != oldWidget.style
        || selectedColor != oldWidget.selectedColor
        || iconColor != oldWidget.iconColor
170
        || textColor != oldWidget.textColor
171 172 173
        || contentPadding != oldWidget.contentPadding
        || tileColor != oldWidget.tileColor
        || selectedTileColor != oldWidget.selectedTileColor;
174 175 176
  }
}

177 178 179 180 181 182 183
/// Where to place the control in widgets that use [ListTile] to position a
/// control next to a label.
///
/// See also:
///
///  * [CheckboxListTile], which combines a [ListTile] with a [Checkbox].
///  * [RadioListTile], which combines a [ListTile] with a [Radio] button.
184
///  * [SwitchListTile], which combines a [ListTile] with a [Switch].
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
enum ListTileControlAffinity {
  /// Position the control on the leading edge, and the secondary widget, if
  /// any, on the trailing edge.
  leading,

  /// Position the control on the trailing edge, and the secondary widget, if
  /// any, on the leading edge.
  trailing,

  /// Position the control relative to the text in the fashion that is typical
  /// for the current platform, and place the secondary widget on the opposite
  /// side.
  platform,
}

200 201
/// A single fixed-height row that typically contains some text as well as
/// a leading or trailing icon.
202
///
203 204
/// {@youtube 560 315 https://www.youtube.com/watch?v=l8dj0yPBvgQ}
///
205
/// A list tile contains one to three lines of text optionally flanked by icons or
206
/// other widgets, such as check boxes. The icons (or other widgets) for the
207
/// tile are defined with the [leading] and [trailing] parameters. The first
208 209 210
/// line of text is not optional and is specified with [title]. The value of
/// [subtitle], which _is_ optional, will occupy the space allocated for an
/// additional line of text, or two lines if [isThreeLine] is true. If [dense]
211
/// is true then the overall height of this tile and the size of the
212 213
/// [DefaultTextStyle]s that wrap the [title] and [subtitle] widget are reduced.
///
214 215 216
/// It is the responsibility of the caller to ensure that [title] does not wrap,
/// and to ensure that [subtitle] doesn't wrap (if [isThreeLine] is false) or
/// wraps to two lines (if it is true).
217
///
218
/// The heights of the [leading] and [trailing] widgets are constrained
219 220
/// according to the
/// [Material spec](https://material.io/design/components/lists.html).
221 222 223 224
/// An exception is made for one-line ListTiles for accessibility. Please
/// see the example below to see how to adhere to both Material spec and
/// accessibility requirements.
///
225 226 227
/// Note that [leading] and [trailing] widgets can expand as far as they wish
/// horizontally, so ensure that they are properly constrained.
///
228 229
/// List tiles are typically used in [ListView]s, or arranged in [Column]s in
/// [Drawer]s and [Card]s.
230 231 232
///
/// Requires one of its ancestors to be a [Material] widget.
///
233
/// {@tool snippet}
234
///
235 236 237 238
/// This example uses a [ListView] to demonstrate different configurations of
/// [ListTile]s in [Card]s.
///
/// ![Different variations of ListTile](https://flutter.github.io/assets-for-api-docs/assets/material/list_tile.png)
239 240
///
/// ```dart
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 275 276 277 278 279 280 281 282 283 284 285 286 287 288
/// ListView(
///   children: const <Widget>[
///     Card(child: ListTile(title: Text('One-line ListTile'))),
///     Card(
///       child: ListTile(
///         leading: FlutterLogo(),
///         title: Text('One-line with leading widget'),
///       ),
///     ),
///     Card(
///       child: ListTile(
///         title: Text('One-line with trailing widget'),
///         trailing: Icon(Icons.more_vert),
///       ),
///     ),
///     Card(
///       child: ListTile(
///         leading: FlutterLogo(),
///         title: Text('One-line with both widgets'),
///         trailing: Icon(Icons.more_vert),
///       ),
///     ),
///     Card(
///       child: ListTile(
///         title: Text('One-line dense ListTile'),
///         dense: true,
///       ),
///     ),
///     Card(
///       child: ListTile(
///         leading: FlutterLogo(size: 56.0),
///         title: Text('Two-line ListTile'),
///         subtitle: Text('Here is a second line'),
///         trailing: Icon(Icons.more_vert),
///       ),
///     ),
///     Card(
///       child: ListTile(
///         leading: FlutterLogo(size: 72.0),
///         title: Text('Three-line ListTile'),
///         subtitle: Text(
///           'A sufficiently long subtitle warrants three lines.'
///         ),
///         trailing: Icon(Icons.more_vert),
///         isThreeLine: true,
///       ),
///     ),
///   ],
289 290
/// )
/// ```
291
/// {@end-tool}
292
/// {@tool snippet}
293 294 295 296 297 298 299 300
///
/// Tiles can be much more elaborate. Here is a tile which can be tapped, but
/// which is disabled when the `_act` variable is not 2. When the tile is
/// tapped, the whole row has an ink splash effect (see [InkWell]).
///
/// ```dart
/// int _act = 1;
/// // ...
301
/// ListTile(
302
///   leading: const Icon(Icons.flight_land),
303
///   title: const Text("Trix's airplane"),
304 305 306 307 308
///   subtitle: _act != 2 ? const Text('The airplane is only in Act II.') : null,
///   enabled: _act == 2,
///   onTap: () { /* react to the tile being tapped */ }
/// )
/// ```
309
/// {@end-tool}
310
///
311 312 313 314 315 316 317 318 319 320 321 322
/// To be accessible, tappable [leading] and [trailing] widgets have to
/// be at least 48x48 in size. However, to adhere to the Material spec,
/// [trailing] and [leading] widgets in one-line ListTiles should visually be
/// at most 32 ([dense]: true) or 40 ([dense]: false) in height, which may
/// conflict with the accessibility requirement.
///
/// For this reason, a one-line ListTile allows the height of [leading]
/// and [trailing] widgets to be constrained by the height of the ListTile.
/// This allows for the creation of tappable [leading] and [trailing] widgets
/// that are large enough, but it is up to the developer to ensure that
/// their widgets follow the Material spec.
///
323
/// {@tool snippet}
324 325
///
/// Here is an example of a one-line, non-[dense] ListTile with a
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
/// tappable leading widget that adheres to accessibility requirements and
/// the Material spec. To adjust the use case below for a one-line, [dense]
/// ListTile, adjust the vertical padding to 8.0.
///
/// ```dart
/// ListTile(
///   leading: GestureDetector(
///     behavior: HitTestBehavior.translucent,
///     onTap: () {},
///     child: Container(
///       width: 48,
///       height: 48,
///       padding: EdgeInsets.symmetric(vertical: 4.0),
///       alignment: Alignment.center,
///       child: CircleAvatar(),
///     ),
///   ),
///   title: Text('title'),
///   dense: false,
/// ),
/// ```
/// {@end-tool}
///
349 350 351 352 353 354
/// ## The ListTile layout isn't exactly what I want
///
/// If the way ListTile pads and positions its elements isn't quite what
/// you're looking for, it's easy to create custom list items with a
/// combination of other widgets, such as [Row]s and [Column]s.
///
355
/// {@tool dartpad --template=stateless_widget_scaffold}
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 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 445 446 447 448 449
///
/// Here is an example of a custom list item that resembles a Youtube related
/// video list item created with [Expanded] and [Container] widgets.
///
/// ![Custom list item a](https://flutter.github.io/assets-for-api-docs/assets/widgets/custom_list_item_a.png)
///
/// ```dart preamble
/// class CustomListItem extends StatelessWidget {
///   const CustomListItem({
///     this.thumbnail,
///     this.title,
///     this.user,
///     this.viewCount,
///   });
///
///   final Widget thumbnail;
///   final String title;
///   final String user;
///   final int viewCount;
///
///   @override
///   Widget build(BuildContext context) {
///     return Padding(
///       padding: const EdgeInsets.symmetric(vertical: 5.0),
///       child: Row(
///         crossAxisAlignment: CrossAxisAlignment.start,
///         children: <Widget>[
///           Expanded(
///             flex: 2,
///             child: thumbnail,
///           ),
///           Expanded(
///             flex: 3,
///             child: _VideoDescription(
///               title: title,
///               user: user,
///               viewCount: viewCount,
///             ),
///           ),
///           const Icon(
///             Icons.more_vert,
///             size: 16.0,
///           ),
///         ],
///       ),
///     );
///   }
/// }
///
/// class _VideoDescription extends StatelessWidget {
///   const _VideoDescription({
///     Key key,
///     this.title,
///     this.user,
///     this.viewCount,
///   }) : super(key: key);
///
///   final String title;
///   final String user;
///   final int viewCount;
///
///   @override
///   Widget build(BuildContext context) {
///     return Padding(
///       padding: const EdgeInsets.fromLTRB(5.0, 0.0, 0.0, 0.0),
///       child: Column(
///         crossAxisAlignment: CrossAxisAlignment.start,
///         children: <Widget>[
///           Text(
///             title,
///             style: const TextStyle(
///               fontWeight: FontWeight.w500,
///               fontSize: 14.0,
///             ),
///           ),
///           const Padding(padding: EdgeInsets.symmetric(vertical: 2.0)),
///           Text(
///             user,
///             style: const TextStyle(fontSize: 10.0),
///           ),
///           const Padding(padding: EdgeInsets.symmetric(vertical: 1.0)),
///           Text(
///             '$viewCount views',
///             style: const TextStyle(fontSize: 10.0),
///           ),
///         ],
///       ),
///     );
///   }
/// }
/// ```
///
/// ```dart
/// Widget build(BuildContext context) {
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
///   return ListView(
///     padding: const EdgeInsets.all(8.0),
///     itemExtent: 106.0,
///     children: <CustomListItem>[
///       CustomListItem(
///         user: 'Flutter',
///         viewCount: 999000,
///         thumbnail: Container(
///           decoration: const BoxDecoration(color: Colors.blue),
///         ),
///         title: 'The Flutter YouTube Channel',
///       ),
///       CustomListItem(
///         user: 'Dash',
///         viewCount: 884000,
///         thumbnail: Container(
///           decoration: const BoxDecoration(color: Colors.yellow),
///         ),
///         title: 'Announcing Flutter 1.0',
///       ),
///     ],
///   );
472 473 474 475
/// }
/// ```
/// {@end-tool}
///
476
/// {@tool dartpad --template=stateless_widget_scaffold}
477
///
478
/// Here is an example of an article list item with multiline titles and
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
/// subtitles. It utilizes [Row]s and [Column]s, as well as [Expanded] and
/// [AspectRatio] widgets to organize its layout.
///
/// ![Custom list item b](https://flutter.github.io/assets-for-api-docs/assets/widgets/custom_list_item_b.png)
///
/// ```dart preamble
/// class _ArticleDescription extends StatelessWidget {
///   _ArticleDescription({
///     Key key,
///     this.title,
///     this.subtitle,
///     this.author,
///     this.publishDate,
///     this.readDuration,
///   }) : super(key: key);
///
///   final String title;
///   final String subtitle;
///   final String author;
///   final String publishDate;
///   final String readDuration;
///
///   @override
///   Widget build(BuildContext context) {
///     return Column(
///       crossAxisAlignment: CrossAxisAlignment.start,
///       children: <Widget>[
///         Expanded(
507
///           flex: 1,
508 509 510 511 512
///           child: Column(
///             crossAxisAlignment: CrossAxisAlignment.start,
///             children: <Widget>[
///               Text(
///                 '$title',
513
///                 maxLines: 2,
514 515 516 517 518 519 520 521
///                 overflow: TextOverflow.ellipsis,
///                 style: const TextStyle(
///                   fontWeight: FontWeight.bold,
///                 ),
///               ),
///               const Padding(padding: EdgeInsets.only(bottom: 2.0)),
///               Text(
///                 '$subtitle',
522
///                 maxLines: 2,
523 524 525 526 527 528 529 530 531 532
///                 overflow: TextOverflow.ellipsis,
///                 style: const TextStyle(
///                   fontSize: 12.0,
///                   color: Colors.black54,
///                 ),
///               ),
///             ],
///           ),
///         ),
///         Expanded(
533
///           flex: 1,
534 535 536 537 538 539 540 541 542 543 544 545
///           child: Column(
///             crossAxisAlignment: CrossAxisAlignment.start,
///             mainAxisAlignment: MainAxisAlignment.end,
///             children: <Widget>[
///               Text(
///                 '$author',
///                 style: const TextStyle(
///                   fontSize: 12.0,
///                   color: Colors.black87,
///                 ),
///               ),
///               Text(
546
///                 '$publishDate - $readDuration',
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
///                 style: const TextStyle(
///                   fontSize: 12.0,
///                   color: Colors.black54,
///                 ),
///               ),
///             ],
///           ),
///         ),
///       ],
///     );
///   }
/// }
///
/// class CustomListItemTwo extends StatelessWidget {
///   CustomListItemTwo({
///     Key key,
///     this.thumbnail,
///     this.title,
///     this.subtitle,
///     this.author,
///     this.publishDate,
///     this.readDuration,
///   }) : super(key: key);
///
///   final Widget thumbnail;
///   final String title;
///   final String subtitle;
///   final String author;
///   final String publishDate;
///   final String readDuration;
///
///   @override
///   Widget build(BuildContext context) {
///     return Padding(
///       padding: const EdgeInsets.symmetric(vertical: 10.0),
///       child: SizedBox(
///         height: 100,
///         child: Row(
///           crossAxisAlignment: CrossAxisAlignment.start,
///           children: <Widget>[
///             AspectRatio(
///               aspectRatio: 1.0,
///               child: thumbnail,
///             ),
///             Expanded(
///               child: Padding(
///                 padding: const EdgeInsets.fromLTRB(20.0, 0.0, 2.0, 0.0),
///                 child: _ArticleDescription(
///                   title: title,
///                   subtitle: subtitle,
///                   author: author,
///                   publishDate: publishDate,
///                   readDuration: readDuration,
///                 ),
///               ),
///             )
///           ],
///         ),
///       ),
///     );
///   }
/// }
/// ```
///
/// ```dart
/// Widget build(BuildContext context) {
///   return ListView(
///     padding: const EdgeInsets.all(10.0),
///     children: <Widget>[
///       CustomListItemTwo(
///         thumbnail: Container(
///           decoration: const BoxDecoration(color: Colors.pink),
///         ),
///         title: 'Flutter 1.0 Launch',
///         subtitle:
///           'Flutter continues to improve and expand its horizons.'
///           'This text should max out at two lines and clip',
///         author: 'Dash',
///         publishDate: 'Dec 28',
///         readDuration: '5 mins',
///       ),
///       CustomListItemTwo(
///         thumbnail: Container(
///           decoration: const BoxDecoration(color: Colors.blue),
///         ),
///         title: 'Flutter 1.2 Release - Continual updates to the framework',
///         subtitle: 'Flutter once again improves and makes updates.',
///         author: 'Flutter',
///         publishDate: 'Feb 26',
///         readDuration: '12 mins',
///       ),
///     ],
///   );
/// }
/// ```
/// {@end-tool}
///
644
/// See also:
645
///
646
///  * [ListTileTheme], which defines visual properties for [ListTile]s.
647 648 649 650
///  * [ListView], which can display an arbitrary number of [ListTile]s
///    in a scrolling list.
///  * [CircleAvatar], which shows an icon representing a person and is often
///    used as the [leading] element of a ListTile.
651
///  * [Card], which can be used with [Column] to show a few [ListTile]s.
652
///  * [Divider], which can be used to separate [ListTile]s.
653
///  * [ListTile.divideTiles], a utility for inserting [Divider]s in between [ListTile]s.
654 655
///  * [CheckboxListTile], [RadioListTile], and [SwitchListTile], widgets
///    that combine [ListTile] with other controls.
656
///  * <https://material.io/design/components/lists.html>
657 658
///  * Cookbook: [Use lists](https://flutter.dev/docs/cookbook/lists/basic-list)
///  * Cookbook: [Implement swipe to dismiss](https://flutter.dev/docs/cookbook/gestures/dismissible)
659 660
class ListTile extends StatelessWidget {
  /// Creates a list tile.
661 662 663 664
  ///
  /// If [isThreeLine] is true, then [subtitle] must not be null.
  ///
  /// Requires one of its ancestors to be a [Material] widget.
665
  const ListTile({
Adam Barth's avatar
Adam Barth committed
666
    Key key,
667 668 669 670
    this.leading,
    this.title,
    this.subtitle,
    this.trailing,
671
    this.isThreeLine = false,
672
    this.dense,
673
    this.visualDensity,
674
    this.shape,
675
    this.contentPadding,
676
    this.enabled = true,
Adam Barth's avatar
Adam Barth committed
677
    this.onTap,
678
    this.onLongPress,
679
    this.mouseCursor,
680
    this.selected = false,
681 682 683
    this.focusColor,
    this.hoverColor,
    this.focusNode,
684
    this.autofocus = false,
685 686
    this.tileColor,
    this.selectedTileColor,
687 688 689
  }) : assert(isThreeLine != null),
       assert(enabled != null),
       assert(selected != null),
690
       assert(autofocus != null),
691
       assert(!isThreeLine || subtitle != null),
692
       super(key: key);
Adam Barth's avatar
Adam Barth committed
693

694 695
  /// A widget to display before the title.
  ///
696
  /// Typically an [Icon] or a [CircleAvatar] widget.
697
  final Widget leading;
698

699
  /// The primary content of the list tile.
700 701
  ///
  /// Typically a [Text] widget.
702
  ///
703 704
  /// This should not wrap. To enforce the single line limit, use
  /// [Text.maxLines].
705
  final Widget title;
706 707 708 709

  /// Additional content displayed below the title.
  ///
  /// Typically a [Text] widget.
710 711 712 713
  ///
  /// If [isThreeLine] is false, this should not wrap.
  ///
  /// If [isThreeLine] is true, this should be configured to take a maximum of
714 715
  /// two lines. For example, you can use [Text.maxLines] to enforce the number
  /// of lines.
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
  ///
  /// The subtitle's default [TextStyle] depends on [TextTheme.bodyText2] except
  /// [TextStyle.color]. The [TextStyle.color] depends on the value of [enabled]
  /// and [selected].
  ///
  /// When [enabled] is false, the text color is set to [ThemeData.disabledColor].
  ///
  /// When [selected] is true, the text color is set to [ListTileTheme.selectedColor]
  /// if it's not null. If [ListTileTheme.selectedColor] is null, the text color
  /// is set to [ThemeData.primaryColor] when [ThemeData.brightness] is
  /// [Brightness.light] and to [ThemeData.accentColor] when it is [Brightness.dark].
  ///
  /// When [selected] is false, the text color is set to [ListTileTheme.textColor]
  /// if it's not null and to [TextTheme.caption]'s color if [ListTileTheme.textColor]
  /// is null.
731
  final Widget subtitle;
732 733 734 735

  /// A widget to display after the title.
  ///
  /// Typically an [Icon] widget.
736 737 738
  ///
  /// To show right-aligned metadata (assuming left-to-right reading order;
  /// left-aligned for right-to-left reading order), consider using a [Row] with
739
  /// [CrossAxisAlignment.baseline] alignment whose first item is [Expanded] and
740 741
  /// whose second child is the metadata text, instead of using the [trailing]
  /// property.
742
  final Widget trailing;
743

744
  /// Whether this list tile is intended to display three lines of text.
745
  ///
746 747 748
  /// If true, then [subtitle] must be non-null (since it is expected to give
  /// the second and third lines of text).
  ///
749
  /// If false, the list tile is treated as having one line if the subtitle is
750
  /// null and treated as having two lines if the subtitle is non-null.
751 752 753
  ///
  /// When using a [Text] widget for [title] and [subtitle], you can enforce
  /// line limits using [Text.maxLines].
Hans Muller's avatar
Hans Muller committed
754
  final bool isThreeLine;
755

756
  /// Whether this list tile is part of a vertically dense list.
757 758
  ///
  /// If this property is null then its value is based on [ListTileTheme.dense].
759 760
  ///
  /// Dense list tiles default to a smaller height.
761
  final bool dense;
762

763 764 765 766 767 768
  /// Defines how compact the list tile's layout will be.
  ///
  /// {@macro flutter.material.themedata.visualDensity}
  ///
  /// See also:
  ///
769 770
  ///  * [ThemeData.visualDensity], which specifies the [visualDensity] for all
  ///    widgets within a [Theme].
771 772
  final VisualDensity visualDensity;

773 774 775 776
  /// The shape of the tile's [InkWell].
  ///
  /// Defines the tile's [InkWell.customBorder].
  ///
777 778 779
  /// If this property is null then [CardTheme.shape] of [ThemeData.cardTheme]
  /// is used. If that's null then the shape will be a [RoundedRectangleBorder]
  /// with a circular corner radius of 4.0.
780 781
  final ShapeBorder shape;

782 783 784 785 786 787 788 789
  /// The tile's internal padding.
  ///
  /// Insets a [ListTile]'s contents: its [leading], [title], [subtitle],
  /// and [trailing] widgets.
  ///
  /// If null, `EdgeInsets.symmetric(horizontal: 16.0)` is used.
  final EdgeInsetsGeometry contentPadding;

790
  /// Whether this list tile is interactive.
791
  ///
792
  /// If false, this list tile is styled with the disabled color from the
793 794
  /// current [Theme] and the [onTap] and [onLongPress] callbacks are
  /// inoperative.
795
  final bool enabled;
796

797
  /// Called when the user taps this list tile.
798 799
  ///
  /// Inoperative if [enabled] is false.
Adam Barth's avatar
Adam Barth committed
800
  final GestureTapCallback onTap;
801

802
  /// Called when the user long-presses on this list tile.
803 804
  ///
  /// Inoperative if [enabled] is false.
Adam Barth's avatar
Adam Barth committed
805 806
  final GestureLongPressCallback onLongPress;

807 808 809 810 811 812 813 814 815 816 817 818
  /// The cursor for a mouse pointer when it enters or is hovering over the
  /// widget.
  ///
  /// If [mouseCursor] is a [MaterialStateProperty<MouseCursor>],
  /// [MaterialStateProperty.resolve] is used for the following [MaterialState]s:
  ///
  ///  * [MaterialState.selected].
  ///  * [MaterialState.disabled].
  ///
  /// If this property is null, [MaterialStateMouseCursor.clickable] will be used.
  final MouseCursor mouseCursor;

819 820 821 822
  /// If this tile is also [enabled] then icons and text are rendered with the same color.
  ///
  /// By default the selected color is the theme's primary color. The selected color
  /// can be overridden with a [ListTileTheme].
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
  ///
  /// {@tool dartpad --template=stateful_widget_scaffold}
  ///
  /// Here is an example of using a [StatefulWidget] to keep track of the
  /// selected index, and using that to set the `selected` property on the
  /// corresponding [ListTile].
  ///
  /// ```dart
  ///   int _selectedIndex;
  ///
  ///   @override
  ///   Widget build(BuildContext context) {
  ///     return ListView.builder(
  ///       itemCount: 10,
  ///       itemBuilder: (BuildContext context, int index) {
  ///         return ListTile(
  ///           title: Text('Item $index'),
  ///           selected: index == _selectedIndex,
  ///           onTap: () {
  ///             setState(() {
  ///               _selectedIndex = index;
  ///             });
  ///           },
  ///         );
  ///       },
  ///     );
  ///   }
  /// ```
  /// {@end-tool}
852 853
  final bool selected;

854 855 856 857 858 859 860 861 862
  /// The color for the tile's [Material] when it has the input focus.
  final Color focusColor;

  /// The color for the tile's [Material] when a pointer is hovering over it.
  final Color hoverColor;

  /// {@macro flutter.widgets.Focus.focusNode}
  final FocusNode focusNode;

863 864 865
  /// {@macro flutter.widgets.Focus.autofocus}
  final bool autofocus;

866
  /// Defines the background color of `ListTile` when [selected] is false.
867
  ///
868 869
  /// When the value is null, the `tileColor` is set to [ListTileTheme.tileColor]
  /// if it's not null and to [Colors.transparent] if it's null.
870 871 872 873
  final Color tileColor;

  /// Defines the background color of `ListTile` when [selected] is true.
  ///
874 875
  /// When the value if null, the `selectedTileColor` is set to [ListTileTheme.selectedTileColor]
  /// if it's not null and to [Colors.transparent] if it's null.
876 877
  final Color selectedTileColor;

878
  /// Add a one pixel border in between each tile. If color isn't specified the
879 880 881 882
  /// [ThemeData.dividerColor] of the context's [Theme] is used.
  ///
  /// See also:
  ///
883
  ///  * [Divider], which you can use to obtain this effect manually.
884 885
  static Iterable<Widget> divideTiles({ BuildContext context, @required Iterable<Widget> tiles, Color color }) sync* {
    assert(tiles != null);
Hans Muller's avatar
Hans Muller committed
886 887
    assert(color != null || context != null);

888
    final Iterator<Widget> iterator = tiles.iterator;
Hans Muller's avatar
Hans Muller committed
889 890
    final bool isNotEmpty = iterator.moveNext();

891 892
    final Decoration decoration = BoxDecoration(
      border: Border(
893 894 895 896
        bottom: Divider.createBorderSide(context, color: color),
      ),
    );

897
    Widget tile = iterator.current;
898
    while (iterator.moveNext()) {
899
      yield DecoratedBox(
900
        position: DecorationPosition.foreground,
901
        decoration: decoration,
902
        child: tile,
Hans Muller's avatar
Hans Muller committed
903
      );
904
      tile = iterator.current;
Hans Muller's avatar
Hans Muller committed
905 906
    }
    if (isNotEmpty)
907
      yield tile;
Hans Muller's avatar
Hans Muller committed
908 909
  }

910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
  Color _iconColor(ThemeData theme, ListTileTheme tileTheme) {
    if (!enabled)
      return theme.disabledColor;

    if (selected && tileTheme?.selectedColor != null)
      return tileTheme.selectedColor;

    if (!selected && tileTheme?.iconColor != null)
      return tileTheme.iconColor;

    switch (theme.brightness) {
      case Brightness.light:
        return selected ? theme.primaryColor : Colors.black45;
      case Brightness.dark:
        return selected ? theme.accentColor : null; // null - use current icon theme color
925
    }
926 927
    assert(theme.brightness != null);
    return null;
Hans Muller's avatar
Hans Muller committed
928 929
  }

930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
  Color _textColor(ThemeData theme, ListTileTheme tileTheme, Color defaultColor) {
    if (!enabled)
      return theme.disabledColor;

    if (selected && tileTheme?.selectedColor != null)
      return tileTheme.selectedColor;

    if (!selected && tileTheme?.textColor != null)
      return tileTheme.textColor;

    if (selected) {
      switch (theme.brightness) {
        case Brightness.light:
          return theme.primaryColor;
        case Brightness.dark:
          return theme.accentColor;
      }
    }
    return defaultColor;
  }

951
  bool _isDenseLayout(ListTileTheme tileTheme) {
952
    return dense ?? tileTheme?.dense ?? false;
953 954 955
  }

  TextStyle _titleTextStyle(ThemeData theme, ListTileTheme tileTheme) {
956 957 958 959
    TextStyle style;
    if (tileTheme != null) {
      switch (tileTheme.style) {
        case ListTileStyle.drawer:
960
          style = theme.textTheme.bodyText1;
961 962
          break;
        case ListTileStyle.list:
963
          style = theme.textTheme.subtitle1;
964 965 966
          break;
      }
    } else {
967
      style = theme.textTheme.subtitle1;
968
    }
969
    final Color color = _textColor(theme, tileTheme, style.color);
970
    return _isDenseLayout(tileTheme)
971 972 973 974 975
      ? style.copyWith(fontSize: 13.0, color: color)
      : style.copyWith(color: color);
  }

  TextStyle _subtitleTextStyle(ThemeData theme, ListTileTheme tileTheme) {
976
    final TextStyle style = theme.textTheme.bodyText2;
977
    final Color color = _textColor(theme, tileTheme, theme.textTheme.caption.color);
978
    return _isDenseLayout(tileTheme)
979 980
      ? style.copyWith(color: color, fontSize: 12.0)
      : style.copyWith(color: color);
Hans Muller's avatar
Hans Muller committed
981 982
  }

983 984 985 986 987 988 989
  Color _tileBackgroundColor(ListTileTheme tileTheme) {
    if (!selected) {
      if (tileColor != null)
        return tileColor;
      if (tileTheme?.tileColor != null)
        return tileTheme.tileColor;
    }
990

991 992 993 994 995 996
    if (selected) {
      if (selectedTileColor != null)
        return selectedTileColor;
      if (tileTheme?.selectedTileColor != null)
        return tileTheme.selectedTileColor;
    }
997 998 999 1000

    return Colors.transparent;
  }

1001
  @override
Adam Barth's avatar
Adam Barth committed
1002
  Widget build(BuildContext context) {
1003
    assert(debugCheckHasMaterial(context));
1004 1005 1006
    final ThemeData theme = Theme.of(context);
    final ListTileTheme tileTheme = ListTileTheme.of(context);

1007 1008
    IconThemeData iconThemeData;
    if (leading != null || trailing != null)
1009
      iconThemeData = IconThemeData(color: _iconColor(theme, tileTheme));
1010

1011
    Widget leadingIcon;
1012
    if (leading != null) {
1013
      leadingIcon = IconTheme.merge(
1014
        data: iconThemeData,
1015 1016
        child: leading,
      );
Adam Barth's avatar
Adam Barth committed
1017 1018
    }

1019
    final TextStyle titleStyle = _titleTextStyle(theme, tileTheme);
1020
    final Widget titleText = AnimatedDefaultTextStyle(
1021
      style: titleStyle,
1022
      duration: kThemeChangeDuration,
1023
      child: title ?? const SizedBox(),
Hans Muller's avatar
Hans Muller committed
1024
    );
1025 1026

    Widget subtitleText;
1027
    TextStyle subtitleStyle;
1028
    if (subtitle != null) {
1029
      subtitleStyle = _subtitleTextStyle(theme, tileTheme);
1030
      subtitleText = AnimatedDefaultTextStyle(
1031
        style: subtitleStyle,
1032 1033
        duration: kThemeChangeDuration,
        child: subtitle,
Hans Muller's avatar
Hans Muller committed
1034 1035
      );
    }
Adam Barth's avatar
Adam Barth committed
1036

1037
    Widget trailingIcon;
1038
    if (trailing != null) {
1039
      trailingIcon = IconTheme.merge(
1040
        data: iconThemeData,
1041 1042
        child: trailing,
      );
Adam Barth's avatar
Adam Barth committed
1043 1044
    }

1045
    const EdgeInsets _defaultContentPadding = EdgeInsets.symmetric(horizontal: 16.0);
1046 1047 1048 1049 1050
    final TextDirection textDirection = Directionality.of(context);
    final EdgeInsets resolvedContentPadding = contentPadding?.resolve(textDirection)
      ?? tileTheme?.contentPadding?.resolve(textDirection)
      ?? _defaultContentPadding;

1051 1052 1053
    final MouseCursor effectiveMouseCursor = MaterialStateProperty.resolveAs<MouseCursor>(
      mouseCursor ?? MaterialStateMouseCursor.clickable,
      <MaterialState>{
1054
        if (!enabled || (onTap == null && onLongPress == null)) MaterialState.disabled,
1055 1056 1057 1058
        if (selected) MaterialState.selected,
      },
    );

1059
    return InkWell(
1060
      customBorder: shape ?? tileTheme.shape,
1061 1062
      onTap: enabled ? onTap : null,
      onLongPress: enabled ? onLongPress : null,
1063
      mouseCursor: effectiveMouseCursor,
1064
      canRequestFocus: enabled,
1065 1066 1067
      focusNode: focusNode,
      focusColor: focusColor,
      hoverColor: hoverColor,
1068
      autofocus: autofocus,
1069
      child: Semantics(
1070
        selected: selected,
1071
        enabled: enabled,
1072
        child: ColoredBox(
1073
          color: _tileBackgroundColor(tileTheme),
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
          child: SafeArea(
            top: false,
            bottom: false,
            minimum: resolvedContentPadding,
            child: _ListTile(
              leading: leadingIcon,
              title: titleText,
              subtitle: subtitleText,
              trailing: trailingIcon,
              isDense: _isDenseLayout(tileTheme),
              visualDensity: visualDensity ?? theme.visualDensity,
              isThreeLine: isThreeLine,
              textDirection: textDirection,
              titleBaselineType: titleStyle.textBaseline,
              subtitleBaselineType: subtitleStyle?.textBaseline,
            ),
1090
          ),
1091
        ),
1092
      ),
Adam Barth's avatar
Adam Barth committed
1093 1094 1095
    );
  }
}
1096

1097 1098 1099 1100 1101 1102 1103 1104
// Identifies the children of a _ListTileElement.
enum _ListTileSlot {
  leading,
  title,
  subtitle,
  trailing,
}

1105 1106 1107 1108 1109 1110 1111
class _ListTile extends RenderObjectWidget {
  const _ListTile({
    Key key,
    this.leading,
    this.title,
    this.subtitle,
    this.trailing,
1112 1113
    @required this.isThreeLine,
    @required this.isDense,
1114
    @required this.visualDensity,
1115 1116 1117 1118 1119
    @required this.textDirection,
    @required this.titleBaselineType,
    this.subtitleBaselineType,
  }) : assert(isThreeLine != null),
       assert(isDense != null),
1120
       assert(visualDensity != null),
1121 1122 1123
       assert(textDirection != null),
       assert(titleBaselineType != null),
       super(key: key);
1124 1125 1126 1127 1128 1129 1130

  final Widget leading;
  final Widget title;
  final Widget subtitle;
  final Widget trailing;
  final bool isThreeLine;
  final bool isDense;
1131
  final VisualDensity visualDensity;
1132 1133 1134
  final TextDirection textDirection;
  final TextBaseline titleBaselineType;
  final TextBaseline subtitleBaselineType;
1135 1136

  @override
1137
  _ListTileElement createElement() => _ListTileElement(this);
1138 1139 1140

  @override
  _RenderListTile createRenderObject(BuildContext context) {
1141
    return _RenderListTile(
1142 1143
      isThreeLine: isThreeLine,
      isDense: isDense,
1144
      visualDensity: visualDensity,
1145 1146 1147
      textDirection: textDirection,
      titleBaselineType: titleBaselineType,
      subtitleBaselineType: subtitleBaselineType,
1148 1149 1150 1151 1152 1153 1154 1155
    );
  }

  @override
  void updateRenderObject(BuildContext context, _RenderListTile renderObject) {
    renderObject
      ..isThreeLine = isThreeLine
      ..isDense = isDense
1156
      ..visualDensity = visualDensity
1157 1158 1159
      ..textDirection = textDirection
      ..titleBaselineType = titleBaselineType
      ..subtitleBaselineType = subtitleBaselineType;
1160 1161 1162
  }
}

1163 1164 1165 1166 1167 1168
class _ListTileElement extends RenderObjectElement {
  _ListTileElement(_ListTile widget) : super(widget);

  final Map<_ListTileSlot, Element> slotToChild = <_ListTileSlot, Element>{};

  @override
1169
  _ListTile get widget => super.widget as _ListTile;
1170 1171

  @override
1172
  _RenderListTile get renderObject => super.renderObject as _RenderListTile;
1173 1174 1175 1176 1177 1178 1179 1180

  @override
  void visitChildren(ElementVisitor visitor) {
    slotToChild.values.forEach(visitor);
  }

  @override
  void forgetChild(Element child) {
1181 1182 1183 1184
    assert(slotToChild.containsValue(child));
    assert(child.slot is _ListTileSlot);
    assert(slotToChild.containsKey(child.slot));
    slotToChild.remove(child.slot);
1185
    super.forgetChild(child);
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
  }

  void _mountChild(Widget widget, _ListTileSlot slot) {
    final Element oldChild = slotToChild[slot];
    final Element newChild = updateChild(oldChild, widget, slot);
    if (oldChild != null) {
      slotToChild.remove(slot);
    }
    if (newChild != null) {
      slotToChild[slot] = newChild;
    }
  }

  @override
  void mount(Element parent, dynamic newSlot) {
    super.mount(parent, newSlot);
    _mountChild(widget.leading, _ListTileSlot.leading);
    _mountChild(widget.title, _ListTileSlot.title);
    _mountChild(widget.subtitle, _ListTileSlot.subtitle);
    _mountChild(widget.trailing, _ListTileSlot.trailing);
  }

  void _updateChild(Widget widget, _ListTileSlot slot) {
    final Element oldChild = slotToChild[slot];
    final Element newChild = updateChild(oldChild, widget, slot);
    if (oldChild != null) {
      slotToChild.remove(slot);
    }
    if (newChild != null) {
      slotToChild[slot] = newChild;
    }
  }

  @override
  void update(_ListTile newWidget) {
    super.update(newWidget);
    assert(widget == newWidget);
    _updateChild(widget.leading, _ListTileSlot.leading);
    _updateChild(widget.title, _ListTileSlot.title);
    _updateChild(widget.subtitle, _ListTileSlot.subtitle);
    _updateChild(widget.trailing, _ListTileSlot.trailing);
  }

1229
  void _updateRenderObject(RenderBox child, _ListTileSlot slot) {
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
    switch (slot) {
      case _ListTileSlot.leading:
        renderObject.leading = child;
        break;
      case _ListTileSlot.title:
        renderObject.title = child;
        break;
      case _ListTileSlot.subtitle:
        renderObject.subtitle = child;
        break;
      case _ListTileSlot.trailing:
        renderObject.trailing = child;
        break;
    }
  }

  @override
1247
  void insertRenderObjectChild(RenderObject child, _ListTileSlot slot) {
1248
    assert(child is RenderBox);
1249
    _updateRenderObject(child as RenderBox, slot);
1250
    assert(renderObject.children.keys.contains(slot));
1251 1252 1253
  }

  @override
1254
  void removeRenderObjectChild(RenderObject child, _ListTileSlot slot) {
1255
    assert(child is RenderBox);
1256
    assert(renderObject.children[slot] == child);
1257
    _updateRenderObject(null, slot);
1258
    assert(!renderObject.children.keys.contains(slot));
1259 1260 1261
  }

  @override
1262
  void moveRenderObjectChild(RenderObject child, dynamic oldSlot, dynamic newSlot) {
1263 1264
    assert(false, 'not reachable');
  }
1265 1266 1267 1268
}

class _RenderListTile extends RenderBox {
  _RenderListTile({
1269
    @required bool isDense,
1270
    @required VisualDensity visualDensity,
1271 1272 1273 1274 1275
    @required bool isThreeLine,
    @required TextDirection textDirection,
    @required TextBaseline titleBaselineType,
    TextBaseline subtitleBaselineType,
  }) : assert(isDense != null),
1276
       assert(visualDensity != null),
1277 1278 1279 1280
       assert(isThreeLine != null),
       assert(textDirection != null),
       assert(titleBaselineType != null),
       _isDense = isDense,
1281
       _visualDensity = visualDensity,
1282
       _isThreeLine = isThreeLine,
1283 1284 1285
       _textDirection = textDirection,
       _titleBaselineType = titleBaselineType,
       _subtitleBaselineType = subtitleBaselineType;
1286 1287 1288

  static const double _minLeadingWidth = 40.0;
  // The horizontal gap between the titles and the leading/trailing widgets
1289
  double get _horizontalTitleGap => 16.0 + visualDensity.horizontal * 2.0;
1290 1291 1292
  // The minimum padding on the top and bottom of the title and subtitle widgets.
  static const double _minVerticalPadding = 4.0;

1293
  final Map<_ListTileSlot, RenderBox> children = <_ListTileSlot, RenderBox>{};
1294 1295 1296 1297

  RenderBox _updateChild(RenderBox oldChild, RenderBox newChild, _ListTileSlot slot) {
    if (oldChild != null) {
      dropChild(oldChild);
1298
      children.remove(slot);
1299 1300
    }
    if (newChild != null) {
1301
      children[slot] = newChild;
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
      adoptChild(newChild);
    }
    return newChild;
  }

  RenderBox _leading;
  RenderBox get leading => _leading;
  set leading(RenderBox value) {
    _leading = _updateChild(_leading, value, _ListTileSlot.leading);
  }

  RenderBox _title;
  RenderBox get title => _title;
  set title(RenderBox value) {
    _title = _updateChild(_title, value, _ListTileSlot.title);
  }

  RenderBox _subtitle;
  RenderBox get subtitle => _subtitle;
  set subtitle(RenderBox value) {
    _subtitle = _updateChild(_subtitle, value, _ListTileSlot.subtitle);
  }

  RenderBox _trailing;
  RenderBox get trailing => _trailing;
  set trailing(RenderBox value) {
    _trailing = _updateChild(_trailing, value, _ListTileSlot.trailing);
  }

  // The returned list is ordered for hit testing.
1332
  Iterable<RenderBox> get _children sync* {
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
    if (leading != null)
      yield leading;
    if (title != null)
      yield title;
    if (subtitle != null)
      yield subtitle;
    if (trailing != null)
      yield trailing;
  }

  bool get isDense => _isDense;
  bool _isDense;
  set isDense(bool value) {
1346
    assert(value != null);
1347 1348 1349 1350 1351 1352
    if (_isDense == value)
      return;
    _isDense = value;
    markNeedsLayout();
  }

1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
  VisualDensity get visualDensity => _visualDensity;
  VisualDensity _visualDensity;
  set visualDensity(VisualDensity value) {
    assert(value != null);
    if (_visualDensity == value)
      return;
    _visualDensity = value;
    markNeedsLayout();
  }

1363 1364 1365
  bool get isThreeLine => _isThreeLine;
  bool _isThreeLine;
  set isThreeLine(bool value) {
1366
    assert(value != null);
1367 1368 1369 1370 1371 1372 1373 1374 1375
    if (_isThreeLine == value)
      return;
    _isThreeLine = value;
    markNeedsLayout();
  }

  TextDirection get textDirection => _textDirection;
  TextDirection _textDirection;
  set textDirection(TextDirection value) {
1376
    assert(value != null);
1377 1378 1379 1380 1381 1382
    if (_textDirection == value)
      return;
    _textDirection = value;
    markNeedsLayout();
  }

1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
  TextBaseline get titleBaselineType => _titleBaselineType;
  TextBaseline _titleBaselineType;
  set titleBaselineType(TextBaseline value) {
    assert(value != null);
    if (_titleBaselineType == value)
      return;
    _titleBaselineType = value;
    markNeedsLayout();
  }

  TextBaseline get subtitleBaselineType => _subtitleBaselineType;
  TextBaseline _subtitleBaselineType;
  set subtitleBaselineType(TextBaseline value) {
    if (_subtitleBaselineType == value)
      return;
    _subtitleBaselineType = value;
    markNeedsLayout();
  }

1402 1403 1404
  @override
  void attach(PipelineOwner owner) {
    super.attach(owner);
1405
    for (final RenderBox child in _children)
1406 1407 1408 1409 1410 1411
      child.attach(owner);
  }

  @override
  void detach() {
    super.detach();
1412
    for (final RenderBox child in _children)
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
      child.detach();
  }

  @override
  void redepthChildren() {
    _children.forEach(redepthChild);
  }

  @override
  void visitChildren(RenderObjectVisitor visitor) {
    _children.forEach(visitor);
  }

  @override
  List<DiagnosticsNode> debugDescribeChildren() {
    final List<DiagnosticsNode> value = <DiagnosticsNode>[];
    void add(RenderBox child, String name) {
      if (child != null)
        value.add(child.toDiagnosticsNode(name: name));
    }
    add(leading, 'leading');
    add(title, 'title');
    add(subtitle, 'subtitle');
    add(trailing, 'trailing');
    return value;
  }

  @override
  bool get sizedByParent => false;

  static double _minWidth(RenderBox box, double height) {
    return box == null ? 0.0 : box.getMinIntrinsicWidth(height);
  }

  static double _maxWidth(RenderBox box, double height) {
    return box == null ? 0.0 : box.getMaxIntrinsicWidth(height);
  }

  @override
  double computeMinIntrinsicWidth(double height) {
    final double leadingWidth = leading != null
      ? math.max(leading.getMinIntrinsicWidth(height), _minLeadingWidth) + _horizontalTitleGap
      : 0.0;
    return leadingWidth
      + math.max(_minWidth(title, height), _minWidth(subtitle, height))
      + _maxWidth(trailing, height);
  }

  @override
  double computeMaxIntrinsicWidth(double height) {
    final double leadingWidth = leading != null
      ? math.max(leading.getMaxIntrinsicWidth(height), _minLeadingWidth) + _horizontalTitleGap
      : 0.0;
    return leadingWidth
      + math.max(_maxWidth(title, height), _maxWidth(subtitle, height))
      + _maxWidth(trailing, height);
  }

  double get _defaultTileHeight {
    final bool hasSubtitle = subtitle != null;
    final bool isTwoLine = !isThreeLine && hasSubtitle;
    final bool isOneLine = !isThreeLine && !hasSubtitle;

1476
    final Offset baseDensity = visualDensity.baseSizeAdjustment;
1477
    if (isOneLine)
1478
      return (isDense ? 48.0 : 56.0) + baseDensity.dy;
1479
    if (isTwoLine)
1480 1481
      return (isDense ? 64.0 : 72.0) + baseDensity.dy;
    return (isDense ? 76.0 : 88.0) + baseDensity.dy;
1482 1483 1484 1485 1486 1487
  }

  @override
  double computeMinIntrinsicHeight(double width) {
    return math.max(
      _defaultTileHeight,
1488
      title.getMinIntrinsicHeight(width) + (subtitle?.getMinIntrinsicHeight(width) ?? 0.0),
1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
    );
  }

  @override
  double computeMaxIntrinsicHeight(double width) {
    return computeMinIntrinsicHeight(width);
  }

  @override
  double computeDistanceToActualBaseline(TextBaseline baseline) {
    assert(title != null);
1500
    final BoxParentData parentData = title.parentData as BoxParentData;
1501
    return parentData.offset.dy + title.getDistanceToActualBaseline(baseline);
1502 1503
  }

1504 1505
  static double _boxBaseline(RenderBox box, TextBaseline baseline) {
    return box.getDistanceToBaseline(baseline);
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
  }

  static Size _layoutBox(RenderBox box, BoxConstraints constraints) {
    if (box == null)
      return Size.zero;
    box.layout(constraints, parentUsesSize: true);
    return box.size;
  }

  static void _positionBox(RenderBox box, Offset offset) {
1516
    final BoxParentData parentData = box.parentData as BoxParentData;
1517 1518 1519 1520 1521 1522 1523
    parentData.offset = offset;
  }

  // All of the dimensions below were taken from the Material Design spec:
  // https://material.io/design/components/lists.html#specs
  @override
  void performLayout() {
1524
    final BoxConstraints constraints = this.constraints;
1525 1526 1527 1528 1529
    final bool hasLeading = leading != null;
    final bool hasSubtitle = subtitle != null;
    final bool hasTrailing = trailing != null;
    final bool isTwoLine = !isThreeLine && hasSubtitle;
    final bool isOneLine = !isThreeLine && !hasSubtitle;
1530
    final Offset densityAdjustment = visualDensity.baseSizeAdjustment;
1531 1532 1533 1534 1535 1536 1537

    final BoxConstraints maxIconHeightConstraint = BoxConstraints(
      // One-line trailing and leading widget heights do not follow
      // Material specifications, but this sizing is required to adhere
      // to accessibility requirements for smallest tappable widget.
      // Two- and three-line trailing widget heights are constrained
      // properly according to the Material spec.
1538
      maxHeight: (isDense ? 48.0 : 56.0) + densityAdjustment.dy,
1539
    );
1540
    final BoxConstraints looseConstraints = constraints.loosen();
1541
    final BoxConstraints iconConstraints = looseConstraints.enforce(maxIconHeightConstraint);
1542 1543

    final double tileWidth = looseConstraints.maxWidth;
1544 1545
    final Size leadingSize = _layoutBox(leading, iconConstraints);
    final Size trailingSize = _layoutBox(trailing, iconConstraints);
1546 1547
    assert(
      tileWidth != leadingSize.width,
1548 1549 1550
      'Leading widget consumes entire tile width. Please use a sized widget, '
      'or consider replacing ListTile with a custom widget '
      '(see https://api.flutter.dev/flutter/material/ListTile-class.html#material.ListTile.4)'
1551 1552 1553
    );
    assert(
      tileWidth != trailingSize.width,
1554 1555 1556
      'Trailing widget consumes entire tile width. Please use a sized widget, '
      'or consider replacing ListTile with a custom widget '
      '(see https://api.flutter.dev/flutter/material/ListTile-class.html#material.ListTile.4)'
1557
    );
1558 1559 1560 1561

    final double titleStart = hasLeading
      ? math.max(_minLeadingWidth, leadingSize.width) + _horizontalTitleGap
      : 0.0;
1562 1563 1564
    final double adjustedTrailingWidth = hasTrailing
        ? math.max(trailingSize.width + _horizontalTitleGap, 32.0)
        : 0.0;
1565
    final BoxConstraints textConstraints = looseConstraints.tighten(
1566
      width: tileWidth - titleStart - adjustedTrailingWidth,
1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582
    );
    final Size titleSize = _layoutBox(title, textConstraints);
    final Size subtitleSize = _layoutBox(subtitle, textConstraints);

    double titleBaseline;
    double subtitleBaseline;
    if (isTwoLine) {
      titleBaseline = isDense ? 28.0 : 32.0;
      subtitleBaseline = isDense ? 48.0 : 52.0;
    } else if (isThreeLine) {
      titleBaseline = isDense ? 22.0 : 28.0;
      subtitleBaseline = isDense ? 42.0 : 48.0;
    } else {
      assert(isOneLine);
    }

1583 1584
    final double defaultTileHeight = _defaultTileHeight;

1585 1586 1587 1588
    double tileHeight;
    double titleY;
    double subtitleY;
    if (!hasSubtitle) {
1589
      tileHeight = math.max(defaultTileHeight, titleSize.height + 2.0 * _minVerticalPadding);
1590 1591
      titleY = (tileHeight - titleSize.height) / 2.0;
    } else {
1592 1593
      assert(subtitleBaselineType != null);
      titleY = titleBaseline - _boxBaseline(title, titleBaselineType);
1594
      subtitleY = subtitleBaseline - _boxBaseline(subtitle, subtitleBaselineType) + visualDensity.vertical * 2.0;
1595
      tileHeight = defaultTileHeight;
1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616

      // If the title and subtitle overlap, move the title upwards by half
      // the overlap and the subtitle down by the same amount, and adjust
      // tileHeight so that both titles fit.
      final double titleOverlap = titleY + titleSize.height - subtitleY;
      if (titleOverlap > 0.0) {
        titleY -= titleOverlap / 2.0;
        subtitleY += titleOverlap / 2.0;
      }

      // If the title or subtitle overflow tileHeight then punt: title
      // and subtitle are arranged in a column, tileHeight = column height plus
      // _minVerticalPadding on top and bottom.
      if (titleY < _minVerticalPadding ||
          (subtitleY + subtitleSize.height + _minVerticalPadding) > tileHeight) {
        tileHeight = titleSize.height + subtitleSize.height + 2.0 * _minVerticalPadding;
        titleY = _minVerticalPadding;
        subtitleY = titleSize.height + _minVerticalPadding;
      }
    }

1617 1618 1619
    // This attempts to implement the redlines for the vertical position of the
    // leading and trailing icons on the spec page:
    //   https://material.io/design/components/lists.html#specs
1620
    // The interpretation for these redlines is as follows:
1621 1622 1623 1624 1625
    //  - For large tiles (> 72dp), both leading and trailing controls should be
    //    a fixed distance from top. As per guidelines this is set to 16dp.
    //  - For smaller tiles, trailing should always be centered. Leading can be
    //    centered or closer to the top. It should never be further than 16dp
    //    to the top.
1626 1627
    double leadingY;
    double trailingY;
1628
    if (tileHeight > 72.0) {
1629 1630
      leadingY = 16.0;
      trailingY = 16.0;
1631 1632 1633
    } else {
      leadingY = math.min((tileHeight - leadingSize.height) / 2.0, 16.0);
      trailingY = (tileHeight - trailingSize.height) / 2.0;
1634
    }
1635 1636 1637 1638

    switch (textDirection) {
      case TextDirection.rtl: {
        if (hasLeading)
1639
          _positionBox(leading, Offset(tileWidth - leadingSize.width, leadingY));
1640
        _positionBox(title, Offset(adjustedTrailingWidth, titleY));
1641
        if (hasSubtitle)
1642
          _positionBox(subtitle, Offset(adjustedTrailingWidth, subtitleY));
1643
        if (hasTrailing)
1644
          _positionBox(trailing, Offset(0.0, trailingY));
1645 1646 1647 1648
        break;
      }
      case TextDirection.ltr: {
        if (hasLeading)
1649 1650
          _positionBox(leading, Offset(0.0, leadingY));
        _positionBox(title, Offset(titleStart, titleY));
1651
        if (hasSubtitle)
1652
          _positionBox(subtitle, Offset(titleStart, subtitleY));
1653
        if (hasTrailing)
1654
          _positionBox(trailing, Offset(tileWidth - trailingSize.width, trailingY));
1655 1656 1657 1658
        break;
      }
    }

1659
    size = constraints.constrain(Size(tileWidth, tileHeight));
1660 1661 1662 1663 1664 1665 1666 1667
    assert(size.width == constraints.constrainWidth(tileWidth));
    assert(size.height == constraints.constrainHeight(tileHeight));
  }

  @override
  void paint(PaintingContext context, Offset offset) {
    void doPaint(RenderBox child) {
      if (child != null) {
1668
        final BoxParentData parentData = child.parentData as BoxParentData;
1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681
        context.paintChild(child, parentData.offset + offset);
      }
    }
    doPaint(leading);
    doPaint(title);
    doPaint(subtitle);
    doPaint(trailing);
  }

  @override
  bool hitTestSelf(Offset position) => true;

  @override
1682
  bool hitTestChildren(BoxHitTestResult result, { @required Offset position }) {
1683
    assert(position != null);
1684
    for (final RenderBox child in _children) {
1685
      final BoxParentData parentData = child.parentData as BoxParentData;
1686 1687 1688 1689 1690 1691 1692 1693 1694
      final bool isHit = result.addWithPaintOffset(
        offset: parentData.offset,
        position: position,
        hitTest: (BoxHitTestResult result, Offset transformed) {
          assert(transformed == position - parentData.offset);
          return child.hitTest(result, position: transformed);
        },
      );
      if (isHit)
1695 1696 1697 1698 1699
        return true;
    }
    return false;
  }
}