list_tile.dart 60.2 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 7
import 'dart:math' as math;

import 'package:flutter/rendering.dart';
8
import 'package:flutter/widgets.dart';
Adam Barth's avatar
Adam Barth committed
9

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

20 21
/// Defines the title font used for [ListTile] descendants of a [ListTileTheme].
///
22 23
/// 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]
24 25
/// text style, which is used by default.
enum ListTileStyle {
Adam Barth's avatar
Adam Barth committed
26
  /// Use a title font that's appropriate for a [ListTile] in a list.
27 28
  list,

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

33
/// An inherited widget that defines color and style parameters for [ListTile]s
34 35 36 37 38 39 40
/// 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].
41
class ListTileTheme extends InheritedTheme {
42 43
  /// Creates a list tile theme that controls the color and style parameters for
  /// [ListTile]s.
44
  const ListTileTheme({
45
    Key? key,
46
    this.dense = false,
47
    this.shape,
48
    this.style = ListTileStyle.list,
49 50 51
    this.selectedColor,
    this.iconColor,
    this.textColor,
52
    this.contentPadding,
53 54
    this.tileColor,
    this.selectedTileColor,
55
    this.enableFeedback,
56 57 58
    this.horizontalTitleGap,
    this.minVerticalPadding,
    this.minLeadingWidth,
59
    required Widget child,
60 61
  }) : super(key: key, child: child);

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({
67 68 69 70 71 72 73 74 75 76
    Key? key,
    bool? dense,
    ShapeBorder? shape,
    ListTileStyle? style,
    Color? selectedColor,
    Color? iconColor,
    Color? textColor,
    EdgeInsetsGeometry? contentPadding,
    Color? tileColor,
    Color? selectedTileColor,
77
    bool? enableFeedback,
78 79 80
    double? horizontalTitleGap,
    double? minVerticalPadding,
    double? minLeadingWidth,
81
    required Widget child,
82 83
  }) {
    assert(child != null);
84
    return Builder(
85 86
      builder: (BuildContext context) {
        final ListTileTheme parent = ListTileTheme.of(context);
87
        return ListTileTheme(
88 89
          key: key,
          dense: dense ?? parent.dense,
90
          shape: shape ?? parent.shape,
91 92 93 94
          style: style ?? parent.style,
          selectedColor: selectedColor ?? parent.selectedColor,
          iconColor: iconColor ?? parent.iconColor,
          textColor: textColor ?? parent.textColor,
95
          contentPadding: contentPadding ?? parent.contentPadding,
96 97
          tileColor: tileColor ?? parent.tileColor,
          selectedTileColor: selectedTileColor ?? parent.selectedTileColor,
98
          enableFeedback: enableFeedback ?? parent.enableFeedback,
99 100 101
          horizontalTitleGap: horizontalTitleGap ?? parent.horizontalTitleGap,
          minVerticalPadding: minVerticalPadding ?? parent.minVerticalPadding,
          minLeadingWidth: minLeadingWidth ?? parent.minLeadingWidth,
102 103 104 105 106 107
          child: child,
        );
      },
    );
  }

108 109 110
  /// If true then [ListTile]s will have the vertically dense layout.
  final bool dense;

111
  /// {@template flutter.material.ListTileTheme.shape}
112
  /// If specified, [shape] defines the [ListTile]'s shape.
113
  /// {@endtemplate}
114
  final ShapeBorder? shape;
115

116 117 118 119
  /// 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.
120
  final Color? selectedColor;
121 122

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

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

128 129
  /// The tile's internal padding.
  ///
130 131
  /// Insets a [ListTile]'s contents: its [ListTile.leading], [ListTile.title],
  /// [ListTile.subtitle], and [ListTile.trailing] widgets.
132
  final EdgeInsetsGeometry? contentPadding;
133

134 135 136 137
  /// If specified, defines the background color for `ListTile` when
  /// [ListTile.selected] is false.
  ///
  /// If [ListTile.tileColor] is provided, [tileColor] is ignored.
138
  final Color? tileColor;
139 140 141 142 143

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

146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
  /// The horizontal gap between the titles and the leading/trailing widgets.
  ///
  /// If specified, overrides the default value of [ListTile.horizontalTitleGap].
  final double? horizontalTitleGap;

  /// The minimum padding on the top and bottom of the title and subtitle widgets.
  ///
  /// If specified, overrides the default value of [ListTile.minVerticalPadding].
  final double? minVerticalPadding;

  /// The minimum width allocated for the [ListTile.leading] widget.
  ///
  /// If specified, overrides the default value of [ListTile.minLeadingWidth].
  final double? minLeadingWidth;

161 162 163 164 165
  /// If specified, defines the feedback property for `ListTile`.
  ///
  /// If [ListTile.enableFeedback] is provided, [enableFeedback] is ignored.
  final bool? enableFeedback;

166 167 168 169 170 171 172 173
  /// 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) {
174 175
    final ListTileTheme? result = context.dependOnInheritedWidgetOfExactType<ListTileTheme>();
    return result ?? const ListTileTheme(child: SizedBox());
176 177
  }

178 179
  @override
  Widget wrap(BuildContext context, Widget child) {
180
    return ListTileTheme(
181
      dense: dense,
182
      shape: shape,
183 184 185 186 187
      style: style,
      selectedColor: selectedColor,
      iconColor: iconColor,
      textColor: textColor,
      contentPadding: contentPadding,
188 189
      tileColor: tileColor,
      selectedTileColor: selectedTileColor,
190
      enableFeedback: enableFeedback,
191 192 193
      horizontalTitleGap: horizontalTitleGap,
      minVerticalPadding: minVerticalPadding,
      minLeadingWidth: minLeadingWidth,
194 195 196 197
      child: child,
    );
  }

198
  @override
199 200
  bool updateShouldNotify(ListTileTheme oldWidget) {
    return dense != oldWidget.dense
201
        || shape != oldWidget.shape
202 203 204
        || style != oldWidget.style
        || selectedColor != oldWidget.selectedColor
        || iconColor != oldWidget.iconColor
205
        || textColor != oldWidget.textColor
206 207
        || contentPadding != oldWidget.contentPadding
        || tileColor != oldWidget.tileColor
208
        || selectedTileColor != oldWidget.selectedTileColor
209 210 211 212
        || enableFeedback != oldWidget.enableFeedback
        || horizontalTitleGap != oldWidget.horizontalTitleGap
        || minVerticalPadding != oldWidget.minVerticalPadding
        || minLeadingWidth != oldWidget.minLeadingWidth;
213 214 215
  }
}

216 217 218 219 220 221 222
/// 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.
223
///  * [SwitchListTile], which combines a [ListTile] with a [Switch].
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
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,
}

239 240
/// A single fixed-height row that typically contains some text as well as
/// a leading or trailing icon.
241
///
242 243
/// {@youtube 560 315 https://www.youtube.com/watch?v=l8dj0yPBvgQ}
///
244
/// A list tile contains one to three lines of text optionally flanked by icons or
245
/// other widgets, such as check boxes. The icons (or other widgets) for the
246
/// tile are defined with the [leading] and [trailing] parameters. The first
247 248 249
/// 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]
250
/// is true then the overall height of this tile and the size of the
251 252
/// [DefaultTextStyle]s that wrap the [title] and [subtitle] widget are reduced.
///
253 254 255
/// 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).
256
///
257
/// The heights of the [leading] and [trailing] widgets are constrained
258 259
/// according to the
/// [Material spec](https://material.io/design/components/lists.html).
260 261 262 263
/// 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.
///
264 265 266
/// Note that [leading] and [trailing] widgets can expand as far as they wish
/// horizontally, so ensure that they are properly constrained.
///
267 268
/// List tiles are typically used in [ListView]s, or arranged in [Column]s in
/// [Drawer]s and [Card]s.
269 270 271
///
/// Requires one of its ancestors to be a [Material] widget.
///
272
/// {@tool snippet}
273
///
274 275 276 277
/// 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)
278 279
///
/// ```dart
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 318 319 320 321 322 323 324 325 326 327
/// 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,
///       ),
///     ),
///   ],
328 329
/// )
/// ```
330
/// {@end-tool}
331
/// {@tool snippet}
332
///
Aayan's avatar
Aayan committed
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
/// To use a [ListTile] within a [Row], it needs to be wrapped in an
/// [Expanded] widget. [ListTile] requires fixed width constraints,
/// whereas a [Row] does not constrain its children.
///
/// ```dart
/// Row(
///   children: const <Widget>[
///     Expanded(
///       child: ListTile(
///         leading: FlutterLogo(),
///         title: Text('These ListTiles are expanded '),
///       ),
///     ),
///     Expanded(
///       child: ListTile(
///         trailing: FlutterLogo(),
///         title: Text('to fill the available space.'),
///       ),
///     ),
///   ],
/// )
/// ```
/// {@end-tool}
/// {@tool snippet}
///
358 359 360 361 362 363 364
/// 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;
/// // ...
365
/// ListTile(
366
///   leading: const Icon(Icons.flight_land),
367
///   title: const Text("Trix's airplane"),
368 369 370 371 372
///   subtitle: _act != 2 ? const Text('The airplane is only in Act II.') : null,
///   enabled: _act == 2,
///   onTap: () { /* react to the tile being tapped */ }
/// )
/// ```
373
/// {@end-tool}
374
///
375 376 377 378 379 380 381 382 383 384 385 386
/// 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.
///
387
/// {@tool snippet}
388 389
///
/// Here is an example of a one-line, non-[dense] ListTile with a
390 391 392 393 394 395 396 397 398 399 400 401
/// 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,
402
///       padding: const EdgeInsets.symmetric(vertical: 4.0),
403
///       alignment: Alignment.center,
404
///       child: const CircleAvatar(),
405 406
///     ),
///   ),
407
///   title: const Text('title'),
408 409 410 411 412
///   dense: false,
/// ),
/// ```
/// {@end-tool}
///
413 414 415 416 417 418
/// ## 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.
///
419
/// {@tool dartpad --template=stateless_widget_scaffold}
420
///
421
/// Here is an example of a custom list item that resembles a YouTube-related
422 423 424 425 426 427 428
/// 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({
429
///     Key? key,
430 431 432 433
///     required this.thumbnail,
///     required this.title,
///     required this.user,
///     required this.viewCount,
434
///   }) : super(key: key);
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
///
///   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({
472 473 474 475
///     Key? key,
///     required this.title,
///     required this.user,
///     required this.viewCount,
476 477 478 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 507 508 509 510 511 512 513 514
///   }) : 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) {
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
///   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',
///       ),
///     ],
///   );
537 538 539 540
/// }
/// ```
/// {@end-tool}
///
541
/// {@tool dartpad --template=stateless_widget_scaffold}
542
///
543
/// Here is an example of an article list item with multiline titles and
544 545 546 547 548 549 550
/// 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 {
551
///   const _ArticleDescription({
552 553 554 555 556 557
///     Key? key,
///     required this.title,
///     required this.subtitle,
///     required this.author,
///     required this.publishDate,
///     required this.readDuration,
558 559 560 561 562 563 564 565 566 567 568 569 570 571
///   }) : 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(
572
///           flex: 1,
573 574 575 576
///           child: Column(
///             crossAxisAlignment: CrossAxisAlignment.start,
///             children: <Widget>[
///               Text(
577
///                 title,
578
///                 maxLines: 2,
579 580 581 582 583 584 585
///                 overflow: TextOverflow.ellipsis,
///                 style: const TextStyle(
///                   fontWeight: FontWeight.bold,
///                 ),
///               ),
///               const Padding(padding: EdgeInsets.only(bottom: 2.0)),
///               Text(
586
///                 subtitle,
587
///                 maxLines: 2,
588 589 590 591 592 593 594 595 596 597
///                 overflow: TextOverflow.ellipsis,
///                 style: const TextStyle(
///                   fontSize: 12.0,
///                   color: Colors.black54,
///                 ),
///               ),
///             ],
///           ),
///         ),
///         Expanded(
598
///           flex: 1,
599 600 601 602 603
///           child: Column(
///             crossAxisAlignment: CrossAxisAlignment.start,
///             mainAxisAlignment: MainAxisAlignment.end,
///             children: <Widget>[
///               Text(
604
///                 author,
605 606 607 608 609 610
///                 style: const TextStyle(
///                   fontSize: 12.0,
///                   color: Colors.black87,
///                 ),
///               ),
///               Text(
611
///                 '$publishDate - $readDuration',
612 613 614 615 616 617 618 619 620 621 622 623 624 625
///                 style: const TextStyle(
///                   fontSize: 12.0,
///                   color: Colors.black54,
///                 ),
///               ),
///             ],
///           ),
///         ),
///       ],
///     );
///   }
/// }
///
/// class CustomListItemTwo extends StatelessWidget {
626
///   const CustomListItemTwo({
627 628 629 630 631 632 633
///     Key? key,
///     required this.thumbnail,
///     required this.title,
///     required this.subtitle,
///     required this.author,
///     required this.publishDate,
///     required this.readDuration,
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
///   }) : 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:
687
///           'Flutter continues to improve and expand its horizons. '
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
///           '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}
///
709
/// See also:
710
///
711
///  * [ListTileTheme], which defines visual properties for [ListTile]s.
712 713 714 715
///  * [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.
716
///  * [Card], which can be used with [Column] to show a few [ListTile]s.
717
///  * [Divider], which can be used to separate [ListTile]s.
718
///  * [ListTile.divideTiles], a utility for inserting [Divider]s in between [ListTile]s.
719 720
///  * [CheckboxListTile], [RadioListTile], and [SwitchListTile], widgets
///    that combine [ListTile] with other controls.
721
///  * <https://material.io/design/components/lists.html>
722 723
///  * Cookbook: [Use lists](https://flutter.dev/docs/cookbook/lists/basic-list)
///  * Cookbook: [Implement swipe to dismiss](https://flutter.dev/docs/cookbook/gestures/dismissible)
724 725
class ListTile extends StatelessWidget {
  /// Creates a list tile.
726 727 728 729
  ///
  /// If [isThreeLine] is true, then [subtitle] must not be null.
  ///
  /// Requires one of its ancestors to be a [Material] widget.
730
  const ListTile({
731
    Key? key,
732 733 734 735
    this.leading,
    this.title,
    this.subtitle,
    this.trailing,
736
    this.isThreeLine = false,
737
    this.dense,
738
    this.visualDensity,
739
    this.shape,
740
    this.contentPadding,
741
    this.enabled = true,
Adam Barth's avatar
Adam Barth committed
742
    this.onTap,
743
    this.onLongPress,
744
    this.mouseCursor,
745
    this.selected = false,
746 747 748
    this.focusColor,
    this.hoverColor,
    this.focusNode,
749
    this.autofocus = false,
750 751
    this.tileColor,
    this.selectedTileColor,
752
    this.enableFeedback,
753 754 755
    this.horizontalTitleGap,
    this.minVerticalPadding,
    this.minLeadingWidth,
756 757 758
  }) : assert(isThreeLine != null),
       assert(enabled != null),
       assert(selected != null),
759
       assert(autofocus != null),
760
       assert(!isThreeLine || subtitle != null),
761
       super(key: key);
Adam Barth's avatar
Adam Barth committed
762

763 764
  /// A widget to display before the title.
  ///
765
  /// Typically an [Icon] or a [CircleAvatar] widget.
766
  final Widget? leading;
767

768
  /// The primary content of the list tile.
769 770
  ///
  /// Typically a [Text] widget.
771
  ///
772 773
  /// This should not wrap. To enforce the single line limit, use
  /// [Text.maxLines].
774
  final Widget? title;
775 776 777 778

  /// Additional content displayed below the title.
  ///
  /// Typically a [Text] widget.
779 780 781 782
  ///
  /// If [isThreeLine] is false, this should not wrap.
  ///
  /// If [isThreeLine] is true, this should be configured to take a maximum of
783 784
  /// two lines. For example, you can use [Text.maxLines] to enforce the number
  /// of lines.
785 786 787 788 789 790 791 792 793 794
  ///
  /// 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 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.
795
  final Widget? subtitle;
796 797 798 799

  /// A widget to display after the title.
  ///
  /// Typically an [Icon] widget.
800 801 802
  ///
  /// To show right-aligned metadata (assuming left-to-right reading order;
  /// left-aligned for right-to-left reading order), consider using a [Row] with
803
  /// [CrossAxisAlignment.baseline] alignment whose first item is [Expanded] and
804 805
  /// whose second child is the metadata text, instead of using the [trailing]
  /// property.
806
  final Widget? trailing;
807

808
  /// Whether this list tile is intended to display three lines of text.
809
  ///
810 811 812
  /// If true, then [subtitle] must be non-null (since it is expected to give
  /// the second and third lines of text).
  ///
813
  /// If false, the list tile is treated as having one line if the subtitle is
814
  /// null and treated as having two lines if the subtitle is non-null.
815 816 817
  ///
  /// When using a [Text] widget for [title] and [subtitle], you can enforce
  /// line limits using [Text.maxLines].
Hans Muller's avatar
Hans Muller committed
818
  final bool isThreeLine;
819

820
  /// Whether this list tile is part of a vertically dense list.
821 822
  ///
  /// If this property is null then its value is based on [ListTileTheme.dense].
823 824
  ///
  /// Dense list tiles default to a smaller height.
825
  final bool? dense;
826

827 828 829 830 831 832
  /// Defines how compact the list tile's layout will be.
  ///
  /// {@macro flutter.material.themedata.visualDensity}
  ///
  /// See also:
  ///
833 834
  ///  * [ThemeData.visualDensity], which specifies the [visualDensity] for all
  ///    widgets within a [Theme].
835
  final VisualDensity? visualDensity;
836

837
  /// The tile's shape.
838
  ///
839
  /// Defines the tile's [InkWell.customBorder] and [Ink.decoration] shape.
840
  ///
841 842
  /// If this property is null then [ListTileTheme.shape] is used.
  /// If that's null then a rectangular [Border] will be used.
843
  final ShapeBorder? shape;
844

845 846 847 848 849 850
  /// 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.
851
  final EdgeInsetsGeometry? contentPadding;
852

853
  /// Whether this list tile is interactive.
854
  ///
855
  /// If false, this list tile is styled with the disabled color from the
856 857
  /// current [Theme] and the [onTap] and [onLongPress] callbacks are
  /// inoperative.
858
  final bool enabled;
859

860
  /// Called when the user taps this list tile.
861 862
  ///
  /// Inoperative if [enabled] is false.
863
  final GestureTapCallback? onTap;
864

865
  /// Called when the user long-presses on this list tile.
866 867
  ///
  /// Inoperative if [enabled] is false.
868
  final GestureLongPressCallback? onLongPress;
Adam Barth's avatar
Adam Barth committed
869

870 871 872 873 874 875 876 877 878 879
  /// 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.
880
  final MouseCursor? mouseCursor;
881

882 883 884 885
  /// 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].
886
  ///
887
  /// {@tool dartpad --template=stateful_widget_scaffold}
888 889 890 891 892 893
  ///
  /// 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
894
  ///   int _selectedIndex = 0;
895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
  ///
  ///   @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}
915 916
  final bool selected;

917
  /// The color for the tile's [Material] when it has the input focus.
918
  final Color? focusColor;
919 920

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

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

926 927 928
  /// {@macro flutter.widgets.Focus.autofocus}
  final bool autofocus;

929
  /// {@template flutter.material.ListTile.tileColor}
930
  /// Defines the background color of `ListTile` when [selected] is false.
931
  ///
932 933
  /// 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.
934
  /// {@endtemplate}
935
  final Color? tileColor;
936 937 938

  /// Defines the background color of `ListTile` when [selected] is true.
  ///
939 940
  /// 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.
941
  final Color? selectedTileColor;
942

943 944 945 946 947 948 949 950 951 952
  /// Whether detected gestures should provide acoustic and/or haptic feedback.
  ///
  /// For example, on Android a tap will produce a clicking sound and a
  /// long-press will produce a short vibration, when feedback is enabled.
  ///
  /// See also:
  ///
  ///  * [Feedback] for providing platform-specific feedback to certain actions.
  final bool? enableFeedback;

953
  /// The horizontal gap between the titles and the leading/trailing widgets.
954 955 956 957
  ///
  /// If null, then the value of [ListTileTheme.horizontalTitleGap] is used. If
  /// that is also null, then a default value of 16 is used.
  final double? horizontalTitleGap;
958 959

  /// The minimum padding on the top and bottom of the title and subtitle widgets.
960 961 962 963
  ///
  /// If null, then the value of [ListTileTheme.minVerticalPadding] is used. If
  /// that is also null, then a default value of 4 is used.
  final double? minVerticalPadding;
964

965 966 967 968 969
  /// The minimum width allocated for the [ListTile.leading] widget.
  ///
  /// If null, then the value of [ListTileTheme.minLeadingWidth] is used. If
  /// that is also null, then a default value of 40 is used.
  final double? minLeadingWidth;
970

971
  /// Add a one pixel border in between each tile. If color isn't specified the
972 973 974 975
  /// [ThemeData.dividerColor] of the context's [Theme] is used.
  ///
  /// See also:
  ///
976
  ///  * [Divider], which you can use to obtain this effect manually.
977
  static Iterable<Widget> divideTiles({ BuildContext? context, required Iterable<Widget> tiles, Color? color }) sync* {
978
    assert(tiles != null);
Hans Muller's avatar
Hans Muller committed
979 980
    assert(color != null || context != null);

981 982 983
    if (tiles.isEmpty)
      return;

984
    final Iterator<Widget> iterator = tiles.iterator;
Hans Muller's avatar
Hans Muller committed
985 986
    final bool isNotEmpty = iterator.moveNext();

987 988
    final Decoration decoration = BoxDecoration(
      border: Border(
989 990 991 992
        bottom: Divider.createBorderSide(context, color: color),
      ),
    );

993
    Widget tile = iterator.current;
994
    while (iterator.moveNext()) {
995
      yield DecoratedBox(
996
        position: DecorationPosition.foreground,
997
        decoration: decoration,
998
        child: tile,
Hans Muller's avatar
Hans Muller committed
999
      );
1000
      tile = iterator.current;
Hans Muller's avatar
Hans Muller committed
1001 1002
    }
    if (isNotEmpty)
1003
      yield tile;
Hans Muller's avatar
Hans Muller committed
1004 1005
  }

1006
  Color? _iconColor(ThemeData theme, ListTileTheme? tileTheme) {
1007 1008 1009 1010
    if (!enabled)
      return theme.disabledColor;

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

    if (!selected && tileTheme?.iconColor != null)
1014
      return tileTheme!.iconColor;
1015 1016 1017

    switch (theme.brightness) {
      case Brightness.light:
1018 1019 1020
        // For the sake of backwards compatibility, the default for unselected
        // tiles is Colors.black45 rather than colorScheme.onSurface.withAlpha(0x73).
        return selected ? theme.colorScheme.primary : Colors.black45;
1021
      case Brightness.dark:
1022
        return selected ? theme.colorScheme.primary : null; // null - use current icon theme color
1023
    }
Hans Muller's avatar
Hans Muller committed
1024 1025
  }

1026
  Color? _textColor(ThemeData theme, ListTileTheme? tileTheme, Color? defaultColor) {
1027 1028 1029 1030
    if (!enabled)
      return theme.disabledColor;

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

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

1036 1037 1038
    if (selected)
      return theme.colorScheme.primary;

1039 1040 1041
    return defaultColor;
  }

1042
  bool _isDenseLayout(ListTileTheme? tileTheme) {
1043
    return dense ?? tileTheme?.dense ?? false;
1044 1045
  }

1046
  TextStyle _titleTextStyle(ThemeData theme, ListTileTheme? tileTheme) {
1047
    final TextStyle style;
1048 1049 1050
    if (tileTheme != null) {
      switch (tileTheme.style) {
        case ListTileStyle.drawer:
1051
          style = theme.textTheme.bodyText1!;
1052 1053
          break;
        case ListTileStyle.list:
1054
          style = theme.textTheme.subtitle1!;
1055 1056 1057
          break;
      }
    } else {
1058
      style = theme.textTheme.subtitle1!;
1059
    }
1060
    final Color? color = _textColor(theme, tileTheme, style.color);
1061
    return _isDenseLayout(tileTheme)
1062 1063 1064 1065
      ? style.copyWith(fontSize: 13.0, color: color)
      : style.copyWith(color: color);
  }

1066 1067 1068
  TextStyle _subtitleTextStyle(ThemeData theme, ListTileTheme? tileTheme) {
    final TextStyle style = theme.textTheme.bodyText2!;
    final Color? color = _textColor(theme, tileTheme, theme.textTheme.caption!.color);
1069
    return _isDenseLayout(tileTheme)
1070 1071
      ? style.copyWith(color: color, fontSize: 12.0)
      : style.copyWith(color: color);
Hans Muller's avatar
Hans Muller committed
1072 1073
  }

1074 1075 1076 1077 1078 1079
  TextStyle _trailingAndLeadingTextStyle(ThemeData theme, ListTileTheme? tileTheme) {
    final TextStyle style = theme.textTheme.bodyText2!;
    final Color? color = _textColor(theme, tileTheme, style.color);
    return style.copyWith(color: color);
  }

1080
  Color _tileBackgroundColor(ListTileTheme? tileTheme) {
1081 1082
    if (!selected) {
      if (tileColor != null)
1083
        return tileColor!;
1084
      if (tileTheme?.tileColor != null)
1085
        return tileTheme!.tileColor!;
1086
    }
1087

1088 1089
    if (selected) {
      if (selectedTileColor != null)
1090
        return selectedTileColor!;
1091
      if (tileTheme?.selectedTileColor != null)
1092
        return tileTheme!.selectedTileColor!;
1093
    }
1094 1095 1096 1097

    return Colors.transparent;
  }

1098
  @override
Adam Barth's avatar
Adam Barth committed
1099
  Widget build(BuildContext context) {
1100
    assert(debugCheckHasMaterial(context));
1101
    final ThemeData theme = Theme.of(context);
1102 1103
    final ListTileTheme tileTheme = ListTileTheme.of(context);

1104
    IconThemeData? iconThemeData;
1105 1106
    TextStyle? leadingAndTrailingTextStyle;
    if (leading != null || trailing != null) {
1107
      iconThemeData = IconThemeData(color: _iconColor(theme, tileTheme));
1108 1109
      leadingAndTrailingTextStyle = _trailingAndLeadingTextStyle(theme, tileTheme);
    }
1110

1111
    Widget? leadingIcon;
1112
    if (leading != null) {
1113 1114 1115 1116 1117 1118 1119
      leadingIcon = AnimatedDefaultTextStyle(
        style: leadingAndTrailingTextStyle!,
        duration: kThemeChangeDuration,
        child: IconTheme.merge(
          data: iconThemeData!,
          child: leading!,
        ),
1120
      );
Adam Barth's avatar
Adam Barth committed
1121 1122
    }

1123
    final TextStyle titleStyle = _titleTextStyle(theme, tileTheme);
1124
    final Widget titleText = AnimatedDefaultTextStyle(
1125
      style: titleStyle,
1126
      duration: kThemeChangeDuration,
1127
      child: title ?? const SizedBox(),
Hans Muller's avatar
Hans Muller committed
1128
    );
1129

1130 1131
    Widget? subtitleText;
    TextStyle? subtitleStyle;
1132
    if (subtitle != null) {
1133
      subtitleStyle = _subtitleTextStyle(theme, tileTheme);
1134
      subtitleText = AnimatedDefaultTextStyle(
1135
        style: subtitleStyle,
1136
        duration: kThemeChangeDuration,
1137
        child: subtitle!,
Hans Muller's avatar
Hans Muller committed
1138 1139
      );
    }
Adam Barth's avatar
Adam Barth committed
1140

1141
    Widget? trailingIcon;
1142
    if (trailing != null) {
1143 1144 1145 1146 1147 1148 1149
      trailingIcon = AnimatedDefaultTextStyle(
        style: leadingAndTrailingTextStyle!,
        duration: kThemeChangeDuration,
        child: IconTheme.merge(
          data: iconThemeData!,
          child: trailing!,
        ),
1150
      );
Adam Barth's avatar
Adam Barth committed
1151 1152
    }

1153
    const EdgeInsets _defaultContentPadding = EdgeInsets.symmetric(horizontal: 16.0);
1154
    final TextDirection textDirection = Directionality.of(context);
1155
    final EdgeInsets resolvedContentPadding = contentPadding?.resolve(textDirection)
1156
      ?? tileTheme.contentPadding?.resolve(textDirection)
1157 1158
      ?? _defaultContentPadding;

1159
    final MouseCursor resolvedMouseCursor = MaterialStateProperty.resolveAs<MouseCursor>(
1160 1161
      mouseCursor ?? MaterialStateMouseCursor.clickable,
      <MaterialState>{
1162
        if (!enabled || (onTap == null && onLongPress == null)) MaterialState.disabled,
1163 1164 1165 1166
        if (selected) MaterialState.selected,
      },
    );

1167
    return InkWell(
1168
      customBorder: shape ?? tileTheme.shape,
1169 1170
      onTap: enabled ? onTap : null,
      onLongPress: enabled ? onLongPress : null,
1171
      mouseCursor: resolvedMouseCursor,
1172
      canRequestFocus: enabled,
1173 1174 1175
      focusNode: focusNode,
      focusColor: focusColor,
      hoverColor: hoverColor,
1176
      autofocus: autofocus,
1177
      enableFeedback: enableFeedback ?? tileTheme.enableFeedback ?? true,
1178
      child: Semantics(
1179
        selected: selected,
1180
        enabled: enabled,
1181 1182 1183 1184 1185
        child: Ink(
          decoration: ShapeDecoration(
            shape: shape ?? tileTheme.shape ?? const Border(),
            color: _tileBackgroundColor(tileTheme),
          ),
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
          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,
1199
              titleBaselineType: titleStyle.textBaseline!,
1200
              subtitleBaselineType: subtitleStyle?.textBaseline,
1201 1202 1203
              horizontalTitleGap: horizontalTitleGap ?? tileTheme.horizontalTitleGap ?? 16,
              minVerticalPadding: minVerticalPadding ?? tileTheme.minVerticalPadding ?? 4,
              minLeadingWidth: minLeadingWidth ?? tileTheme.minLeadingWidth ?? 40,
1204
            ),
1205
          ),
1206
        ),
1207
      ),
Adam Barth's avatar
Adam Barth committed
1208 1209 1210
    );
  }
}
1211

1212 1213 1214 1215 1216 1217 1218 1219
// Identifies the children of a _ListTileElement.
enum _ListTileSlot {
  leading,
  title,
  subtitle,
  trailing,
}

1220 1221
class _ListTile extends RenderObjectWidget {
  const _ListTile({
1222
    Key? key,
1223
    this.leading,
1224
    required this.title,
1225 1226
    this.subtitle,
    this.trailing,
1227 1228 1229 1230 1231
    required this.isThreeLine,
    required this.isDense,
    required this.visualDensity,
    required this.textDirection,
    required this.titleBaselineType,
1232 1233 1234
    required this.horizontalTitleGap,
    required this.minVerticalPadding,
    required this.minLeadingWidth,
1235 1236 1237
    this.subtitleBaselineType,
  }) : assert(isThreeLine != null),
       assert(isDense != null),
1238
       assert(visualDensity != null),
1239 1240
       assert(textDirection != null),
       assert(titleBaselineType != null),
1241 1242 1243
       assert(horizontalTitleGap != null),
       assert(minVerticalPadding != null),
       assert(minLeadingWidth != null),
1244
       super(key: key);
1245

1246
  final Widget? leading;
1247
  final Widget title;
1248 1249
  final Widget? subtitle;
  final Widget? trailing;
1250 1251
  final bool isThreeLine;
  final bool isDense;
1252
  final VisualDensity visualDensity;
1253 1254
  final TextDirection textDirection;
  final TextBaseline titleBaselineType;
1255
  final TextBaseline? subtitleBaselineType;
1256 1257 1258
  final double horizontalTitleGap;
  final double minVerticalPadding;
  final double minLeadingWidth;
1259 1260

  @override
1261
  _ListTileElement createElement() => _ListTileElement(this);
1262 1263 1264

  @override
  _RenderListTile createRenderObject(BuildContext context) {
1265
    return _RenderListTile(
1266 1267
      isThreeLine: isThreeLine,
      isDense: isDense,
1268
      visualDensity: visualDensity,
1269 1270 1271
      textDirection: textDirection,
      titleBaselineType: titleBaselineType,
      subtitleBaselineType: subtitleBaselineType,
1272 1273 1274
      horizontalTitleGap: horizontalTitleGap,
      minVerticalPadding: minVerticalPadding,
      minLeadingWidth: minLeadingWidth,
1275 1276 1277 1278 1279 1280 1281 1282
    );
  }

  @override
  void updateRenderObject(BuildContext context, _RenderListTile renderObject) {
    renderObject
      ..isThreeLine = isThreeLine
      ..isDense = isDense
1283
      ..visualDensity = visualDensity
1284 1285
      ..textDirection = textDirection
      ..titleBaselineType = titleBaselineType
1286 1287 1288 1289
      ..subtitleBaselineType = subtitleBaselineType
      ..horizontalTitleGap = horizontalTitleGap
      ..minLeadingWidth = minLeadingWidth
      ..minVerticalPadding = minVerticalPadding;
1290 1291 1292
  }
}

1293 1294 1295 1296 1297 1298
class _ListTileElement extends RenderObjectElement {
  _ListTileElement(_ListTile widget) : super(widget);

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

  @override
1299
  _ListTile get widget => super.widget as _ListTile;
1300 1301

  @override
1302
  _RenderListTile get renderObject => super.renderObject as _RenderListTile;
1303 1304 1305 1306 1307 1308 1309 1310

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

  @override
  void forgetChild(Element child) {
1311 1312 1313 1314
    assert(slotToChild.containsValue(child));
    assert(child.slot is _ListTileSlot);
    assert(slotToChild.containsKey(child.slot));
    slotToChild.remove(child.slot);
1315
    super.forgetChild(child);
1316 1317
  }

1318 1319 1320
  void _mountChild(Widget? widget, _ListTileSlot slot) {
    final Element? oldChild = slotToChild[slot];
    final Element? newChild = updateChild(oldChild, widget, slot);
1321 1322 1323 1324 1325 1326 1327 1328 1329
    if (oldChild != null) {
      slotToChild.remove(slot);
    }
    if (newChild != null) {
      slotToChild[slot] = newChild;
    }
  }

  @override
1330
  void mount(Element? parent, Object? newSlot) {
1331 1332 1333 1334 1335 1336 1337
    super.mount(parent, newSlot);
    _mountChild(widget.leading, _ListTileSlot.leading);
    _mountChild(widget.title, _ListTileSlot.title);
    _mountChild(widget.subtitle, _ListTileSlot.subtitle);
    _mountChild(widget.trailing, _ListTileSlot.trailing);
  }

1338 1339 1340
  void _updateChild(Widget? widget, _ListTileSlot slot) {
    final Element? oldChild = slotToChild[slot];
    final Element? newChild = updateChild(oldChild, widget, slot);
1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358
    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);
  }

1359
  void _updateRenderObject(RenderBox? child, _ListTileSlot slot) {
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
    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
1377
  void insertRenderObjectChild(RenderObject child, _ListTileSlot slot) {
1378
    assert(child is RenderBox);
1379
    _updateRenderObject(child as RenderBox, slot);
1380
    assert(renderObject.children.keys.contains(slot));
1381 1382 1383
  }

  @override
1384
  void removeRenderObjectChild(RenderObject child, _ListTileSlot slot) {
1385
    assert(child is RenderBox);
1386
    assert(renderObject.children[slot] == child);
1387
    _updateRenderObject(null, slot);
1388
    assert(!renderObject.children.keys.contains(slot));
1389 1390 1391
  }

  @override
1392
  void moveRenderObjectChild(RenderObject child, Object? oldSlot, Object? newSlot) {
1393 1394
    assert(false, 'not reachable');
  }
1395 1396 1397 1398
}

class _RenderListTile extends RenderBox {
  _RenderListTile({
1399 1400 1401 1402 1403 1404
    required bool isDense,
    required VisualDensity visualDensity,
    required bool isThreeLine,
    required TextDirection textDirection,
    required TextBaseline titleBaselineType,
    TextBaseline? subtitleBaselineType,
1405 1406 1407
    required double horizontalTitleGap,
    required double minVerticalPadding,
    required double minLeadingWidth,
1408
  }) : assert(isDense != null),
1409
       assert(visualDensity != null),
1410 1411 1412
       assert(isThreeLine != null),
       assert(textDirection != null),
       assert(titleBaselineType != null),
1413 1414 1415
       assert(horizontalTitleGap != null),
       assert(minVerticalPadding != null),
       assert(minLeadingWidth != null),
1416
       _isDense = isDense,
1417
       _visualDensity = visualDensity,
1418
       _isThreeLine = isThreeLine,
1419 1420
       _textDirection = textDirection,
       _titleBaselineType = titleBaselineType,
1421
       _subtitleBaselineType = subtitleBaselineType,
1422
       _horizontalTitleGap = horizontalTitleGap,
1423 1424
       _minVerticalPadding = minVerticalPadding,
       _minLeadingWidth = minLeadingWidth;
1425

1426
  final Map<_ListTileSlot, RenderBox> children = <_ListTileSlot, RenderBox>{};
1427

1428
  RenderBox? _updateChild(RenderBox? oldChild, RenderBox? newChild, _ListTileSlot slot) {
1429 1430
    if (oldChild != null) {
      dropChild(oldChild);
1431
      children.remove(slot);
1432 1433
    }
    if (newChild != null) {
1434
      children[slot] = newChild;
1435 1436 1437 1438 1439
      adoptChild(newChild);
    }
    return newChild;
  }

1440 1441 1442
  RenderBox? _leading;
  RenderBox? get leading => _leading;
  set leading(RenderBox? value) {
1443 1444 1445
    _leading = _updateChild(_leading, value, _ListTileSlot.leading);
  }

1446 1447 1448
  RenderBox? _title;
  RenderBox? get title => _title;
  set title(RenderBox? value) {
1449 1450 1451
    _title = _updateChild(_title, value, _ListTileSlot.title);
  }

1452 1453 1454
  RenderBox? _subtitle;
  RenderBox? get subtitle => _subtitle;
  set subtitle(RenderBox? value) {
1455 1456 1457
    _subtitle = _updateChild(_subtitle, value, _ListTileSlot.subtitle);
  }

1458 1459 1460
  RenderBox? _trailing;
  RenderBox? get trailing => _trailing;
  set trailing(RenderBox? value) {
1461 1462 1463 1464
    _trailing = _updateChild(_trailing, value, _ListTileSlot.trailing);
  }

  // The returned list is ordered for hit testing.
1465
  Iterable<RenderBox> get _children sync* {
1466
    if (leading != null)
1467
      yield leading!;
1468
    if (title != null)
1469
      yield title!;
1470
    if (subtitle != null)
1471
      yield subtitle!;
1472
    if (trailing != null)
1473
      yield trailing!;
1474 1475 1476 1477 1478
  }

  bool get isDense => _isDense;
  bool _isDense;
  set isDense(bool value) {
1479
    assert(value != null);
1480 1481 1482 1483 1484 1485
    if (_isDense == value)
      return;
    _isDense = value;
    markNeedsLayout();
  }

1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
  VisualDensity get visualDensity => _visualDensity;
  VisualDensity _visualDensity;
  set visualDensity(VisualDensity value) {
    assert(value != null);
    if (_visualDensity == value)
      return;
    _visualDensity = value;
    markNeedsLayout();
  }

1496 1497 1498
  bool get isThreeLine => _isThreeLine;
  bool _isThreeLine;
  set isThreeLine(bool value) {
1499
    assert(value != null);
1500 1501 1502 1503 1504 1505 1506 1507 1508
    if (_isThreeLine == value)
      return;
    _isThreeLine = value;
    markNeedsLayout();
  }

  TextDirection get textDirection => _textDirection;
  TextDirection _textDirection;
  set textDirection(TextDirection value) {
1509
    assert(value != null);
1510 1511 1512 1513 1514 1515
    if (_textDirection == value)
      return;
    _textDirection = value;
    markNeedsLayout();
  }

1516 1517 1518 1519 1520 1521 1522 1523 1524 1525
  TextBaseline get titleBaselineType => _titleBaselineType;
  TextBaseline _titleBaselineType;
  set titleBaselineType(TextBaseline value) {
    assert(value != null);
    if (_titleBaselineType == value)
      return;
    _titleBaselineType = value;
    markNeedsLayout();
  }

1526 1527 1528
  TextBaseline? get subtitleBaselineType => _subtitleBaselineType;
  TextBaseline? _subtitleBaselineType;
  set subtitleBaselineType(TextBaseline? value) {
1529 1530 1531 1532 1533 1534
    if (_subtitleBaselineType == value)
      return;
    _subtitleBaselineType = value;
    markNeedsLayout();
  }

1535 1536
  double get horizontalTitleGap => _horizontalTitleGap;
  double _horizontalTitleGap;
1537
  double get _effectiveHorizontalTitleGap => _horizontalTitleGap + visualDensity.horizontal * 2.0;
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568

  set horizontalTitleGap(double value) {
    assert(value != null);
    if (_horizontalTitleGap == value)
      return;
    _horizontalTitleGap = value;
    markNeedsLayout();
  }

  double get minVerticalPadding => _minVerticalPadding;
  double _minVerticalPadding;

  set minVerticalPadding(double value) {
    assert(value != null);
    if (_minVerticalPadding == value)
      return;
    _minVerticalPadding = value;
    markNeedsLayout();
  }

  double get minLeadingWidth => _minLeadingWidth;
  double _minLeadingWidth;

  set minLeadingWidth(double value) {
    assert(value != null);
    if (_minLeadingWidth == value)
      return;
    _minLeadingWidth = value;
    markNeedsLayout();
  }

1569 1570 1571
  @override
  void attach(PipelineOwner owner) {
    super.attach(owner);
1572
    for (final RenderBox child in _children)
1573 1574 1575 1576 1577 1578
      child.attach(owner);
  }

  @override
  void detach() {
    super.detach();
1579
    for (final RenderBox child in _children)
1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595
      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>[];
1596
    void add(RenderBox? child, String name) {
1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609
      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;

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

1614
  static double _maxWidth(RenderBox? box, double height) {
1615 1616 1617 1618 1619 1620
    return box == null ? 0.0 : box.getMaxIntrinsicWidth(height);
  }

  @override
  double computeMinIntrinsicWidth(double height) {
    final double leadingWidth = leading != null
1621
      ? math.max(leading!.getMinIntrinsicWidth(height), _minLeadingWidth) + _effectiveHorizontalTitleGap
1622 1623 1624 1625 1626 1627 1628 1629 1630
      : 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
1631
      ? math.max(leading!.getMaxIntrinsicWidth(height), _minLeadingWidth) + _effectiveHorizontalTitleGap
1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642
      : 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;

1643
    final Offset baseDensity = visualDensity.baseSizeAdjustment;
1644
    if (isOneLine)
1645
      return (isDense ? 48.0 : 56.0) + baseDensity.dy;
1646
    if (isTwoLine)
1647 1648
      return (isDense ? 64.0 : 72.0) + baseDensity.dy;
    return (isDense ? 76.0 : 88.0) + baseDensity.dy;
1649 1650 1651 1652 1653 1654
  }

  @override
  double computeMinIntrinsicHeight(double width) {
    return math.max(
      _defaultTileHeight,
1655
      title!.getMinIntrinsicHeight(width) + (subtitle?.getMinIntrinsicHeight(width) ?? 0.0),
1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666
    );
  }

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

  @override
  double computeDistanceToActualBaseline(TextBaseline baseline) {
    assert(title != null);
1667 1668
    final BoxParentData parentData = title!.parentData! as BoxParentData;
    return parentData.offset.dy + title!.getDistanceToActualBaseline(baseline)!;
1669 1670
  }

1671
  static double? _boxBaseline(RenderBox box, TextBaseline baseline) {
1672
    return box.getDistanceToBaseline(baseline);
1673 1674
  }

1675
  static Size _layoutBox(RenderBox? box, BoxConstraints constraints) {
1676 1677 1678 1679 1680 1681 1682
    if (box == null)
      return Size.zero;
    box.layout(constraints, parentUsesSize: true);
    return box.size;
  }

  static void _positionBox(RenderBox box, Offset offset) {
1683
    final BoxParentData parentData = box.parentData! as BoxParentData;
1684 1685 1686
    parentData.offset = offset;
  }

1687 1688 1689
  @override
  Size computeDryLayout(BoxConstraints constraints) {
    assert(debugCannotComputeDryLayout(
1690
      reason: 'Layout requires baseline metrics, which are only available after a full layout.',
1691
    ));
1692
    return Size.zero;
1693 1694
  }

1695 1696 1697 1698
  // All of the dimensions below were taken from the Material Design spec:
  // https://material.io/design/components/lists.html#specs
  @override
  void performLayout() {
1699
    final BoxConstraints constraints = this.constraints;
1700 1701 1702 1703 1704
    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;
1705
    final Offset densityAdjustment = visualDensity.baseSizeAdjustment;
1706 1707 1708 1709 1710 1711 1712

    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.
1713
      maxHeight: (isDense ? 48.0 : 56.0) + densityAdjustment.dy,
1714
    );
1715
    final BoxConstraints looseConstraints = constraints.loosen();
1716
    final BoxConstraints iconConstraints = looseConstraints.enforce(maxIconHeightConstraint);
1717 1718

    final double tileWidth = looseConstraints.maxWidth;
1719 1720
    final Size leadingSize = _layoutBox(leading, iconConstraints);
    final Size trailingSize = _layoutBox(trailing, iconConstraints);
1721
    assert(
1722
      tileWidth != leadingSize.width || tileWidth == 0.0,
1723 1724
      'Leading widget consumes entire tile width. Please use a sized widget, '
      'or consider replacing ListTile with a custom widget '
1725
      '(see https://api.flutter.dev/flutter/material/ListTile-class.html#material.ListTile.4)',
1726 1727
    );
    assert(
1728
      tileWidth != trailingSize.width || tileWidth == 0.0,
1729 1730
      'Trailing widget consumes entire tile width. Please use a sized widget, '
      'or consider replacing ListTile with a custom widget '
1731
      '(see https://api.flutter.dev/flutter/material/ListTile-class.html#material.ListTile.4)',
1732
    );
1733 1734

    final double titleStart = hasLeading
1735
      ? math.max(_minLeadingWidth, leadingSize.width) + _effectiveHorizontalTitleGap
1736
      : 0.0;
1737
    final double adjustedTrailingWidth = hasTrailing
1738
        ? math.max(trailingSize.width + _effectiveHorizontalTitleGap, 32.0)
1739
        : 0.0;
1740
    final BoxConstraints textConstraints = looseConstraints.tighten(
1741
      width: tileWidth - titleStart - adjustedTrailingWidth,
1742 1743 1744 1745
    );
    final Size titleSize = _layoutBox(title, textConstraints);
    final Size subtitleSize = _layoutBox(subtitle, textConstraints);

1746 1747
    double? titleBaseline;
    double? subtitleBaseline;
1748 1749 1750 1751 1752 1753 1754 1755 1756 1757
    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);
    }

1758 1759
    final double defaultTileHeight = _defaultTileHeight;

1760 1761
    double tileHeight;
    double titleY;
1762
    double? subtitleY;
1763
    if (!hasSubtitle) {
1764
      tileHeight = math.max(defaultTileHeight, titleSize.height + 2.0 * _minVerticalPadding);
1765 1766
      titleY = (tileHeight - titleSize.height) / 2.0;
    } else {
1767
      assert(subtitleBaselineType != null);
1768 1769
      titleY = titleBaseline! - _boxBaseline(title!, titleBaselineType)!;
      subtitleY = subtitleBaseline! - _boxBaseline(subtitle!, subtitleBaselineType!)! + visualDensity.vertical * 2.0;
1770
      tileHeight = defaultTileHeight;
1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791

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

1792 1793 1794
    // 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
1795
    // The interpretation for these redlines is as follows:
1796 1797 1798 1799 1800
    //  - 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.
1801 1802
    final double leadingY;
    final double trailingY;
1803
    if (tileHeight > 72.0) {
1804 1805
      leadingY = 16.0;
      trailingY = 16.0;
1806 1807 1808
    } else {
      leadingY = math.min((tileHeight - leadingSize.height) / 2.0, 16.0);
      trailingY = (tileHeight - trailingSize.height) / 2.0;
1809
    }
1810 1811 1812 1813

    switch (textDirection) {
      case TextDirection.rtl: {
        if (hasLeading)
1814 1815
          _positionBox(leading!, Offset(tileWidth - leadingSize.width, leadingY));
        _positionBox(title!, Offset(adjustedTrailingWidth, titleY));
1816
        if (hasSubtitle)
1817
          _positionBox(subtitle!, Offset(adjustedTrailingWidth, subtitleY!));
1818
        if (hasTrailing)
1819
          _positionBox(trailing!, Offset(0.0, trailingY));
1820 1821 1822 1823
        break;
      }
      case TextDirection.ltr: {
        if (hasLeading)
1824 1825
          _positionBox(leading!, Offset(0.0, leadingY));
        _positionBox(title!, Offset(titleStart, titleY));
1826
        if (hasSubtitle)
1827
          _positionBox(subtitle!, Offset(titleStart, subtitleY!));
1828
        if (hasTrailing)
1829
          _positionBox(trailing!, Offset(tileWidth - trailingSize.width, trailingY));
1830 1831 1832 1833
        break;
      }
    }

1834
    size = constraints.constrain(Size(tileWidth, tileHeight));
1835 1836 1837 1838 1839 1840
    assert(size.width == constraints.constrainWidth(tileWidth));
    assert(size.height == constraints.constrainHeight(tileHeight));
  }

  @override
  void paint(PaintingContext context, Offset offset) {
1841
    void doPaint(RenderBox? child) {
1842
      if (child != null) {
1843
        final BoxParentData parentData = child.parentData! as BoxParentData;
1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856
        context.paintChild(child, parentData.offset + offset);
      }
    }
    doPaint(leading);
    doPaint(title);
    doPaint(subtitle);
    doPaint(trailing);
  }

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

  @override
1857
  bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
1858
    assert(position != null);
1859
    for (final RenderBox child in _children) {
1860
      final BoxParentData parentData = child.parentData! as BoxParentData;
1861 1862 1863 1864 1865 1866 1867 1868 1869
      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)
1870 1871 1872 1873 1874
        return true;
    }
    return false;
  }
}