list_tile.dart 58 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 'color_scheme.dart';
11
import 'colors.dart';
12
import 'constants.dart';
13
import 'debug.dart';
14
import 'divider.dart';
15 16
import 'icon_button.dart';
import 'icon_button_theme.dart';
17
import 'ink_decoration.dart';
Adam Barth's avatar
Adam Barth committed
18
import 'ink_well.dart';
19
import 'list_tile_theme.dart';
20
import 'material_state.dart';
21
import 'text_theme.dart';
Hans Muller's avatar
Hans Muller committed
22
import 'theme.dart';
23
import 'theme_data.dart';
Adam Barth's avatar
Adam Barth committed
24

25 26 27
// Examples can assume:
// int _act = 1;

28 29
/// Defines the title font used for [ListTile] descendants of a [ListTileTheme].
///
30 31
/// List tiles that appear in a [Drawer] use the theme's [TextTheme.bodyLarge]
/// text style, which is a little smaller than the theme's [TextTheme.titleMedium]
32 33
/// text style, which is used by default.
enum ListTileStyle {
Adam Barth's avatar
Adam Barth committed
34
  /// Use a title font that's appropriate for a [ListTile] in a list.
35 36
  list,

Adam Barth's avatar
Adam Barth committed
37
  /// Use a title font that's appropriate for a [ListTile] that appears in a [Drawer].
38
  drawer,
39 40
}

41 42
/// Where to place the control in widgets that use [ListTile] to position a
/// control next to a label.
43
///
44
/// See also:
45
///
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
///  * [CheckboxListTile], which combines a [ListTile] with a [Checkbox].
///  * [RadioListTile], which combines a [ListTile] with a [Radio] button.
///  * [SwitchListTile], which combines a [ListTile] with a [Switch].
///  * [ExpansionTile], which combines a [ListTile] with a button that expands
///    or collapses the tile to reveal or hide the children.
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,
}

66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
/// Defines how [ListTile.leading] and [ListTile.trailing] are
/// vertically aligned relative to the [ListTile]'s titles
/// ([ListTile.title] and [ListTile.subtitle]).
///
/// See also:
///
///  * [ListTile.titleAlignment], to configure the title alignment for an
///    individual [ListTile].
///  * [ListTileThemeData.titleAlignment], to configure the title alignment
///    for all of the [ListTile]s under a [ListTileTheme].
///  * [ThemeData.listTileTheme], to configure the [ListTileTheme]
///    for an entire app.
enum ListTileTitleAlignment {
  /// The top of the [ListTile.leading] and [ListTile.trailing] widgets are
  /// placed [ListTile.minVerticalPadding] below the top of the [ListTile.title]
  /// if [ListTile.isThreeLine] is true, otherwise they're centered relative
  /// to the [ListTile.title] and [ListTile.subtitle] widgets.
  ///
  /// This is the default when [ThemeData.useMaterial3] is true.
  threeLine,

  /// The tops of the [ListTile.leading] and [ListTile.trailing] widgets are
  /// placed 16 units below the top of the [ListTile.title]
  /// if the titles' overall height is greater than 72, otherwise they're
  /// centered relative to the [ListTile.title] and [ListTile.subtitle] widgets.
  ///
  /// This is the default when [ThemeData.useMaterial3] is false.
  titleHeight,

  /// The tops of the [ListTile.leading] and [ListTile.trailing] widgets are
  /// placed [ListTile.minVerticalPadding] below the top of the [ListTile.title].
  top,

  /// The [ListTile.leading] and [ListTile.trailing] widgets are
  /// centered relative to the [ListTile]'s titles.
  center,

  /// The bottoms of the [ListTile.leading] and [ListTile.trailing] widgets are
  /// placed [ListTile.minVerticalPadding] above the bottom of the [ListTile]'s
  /// titles.
  bottom,
}

109 110
/// A single fixed-height row that typically contains some text as well as
/// a leading or trailing icon.
111
///
112 113
/// {@youtube 560 315 https://www.youtube.com/watch?v=l8dj0yPBvgQ}
///
114
/// A list tile contains one to three lines of text optionally flanked by icons or
115
/// other widgets, such as check boxes. The icons (or other widgets) for the
116
/// tile are defined with the [leading] and [trailing] parameters. The first
117 118 119
/// 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]
120
/// is true then the overall height of this tile and the size of the
121 122
/// [DefaultTextStyle]s that wrap the [title] and [subtitle] widget are reduced.
///
123 124 125
/// 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).
126
///
127
/// The heights of the [leading] and [trailing] widgets are constrained
128 129
/// according to the
/// [Material spec](https://material.io/design/components/lists.html).
130 131 132 133
/// 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.
///
134
/// The [leading] and [trailing] widgets can expand as far as they wish
135 136
/// horizontally, so ensure that they are properly constrained.
///
137 138
/// List tiles are typically used in [ListView]s, or arranged in [Column]s in
/// [Drawer]s and [Card]s.
139
///
140 141 142 143 144 145
/// This widget requires a [Material] widget ancestor in the tree to paint
/// itself on, which is typically provided by the app's [Scaffold].
/// The [tileColor], [selectedTileColor], [focusColor], and [hoverColor]
/// are not painted by the [ListTile] itself but by the [Material] widget
/// ancestor. In this case, one can wrap a [Material] widget around the
/// [ListTile], e.g.:
146
///
147
/// {@tool snippet}
148
/// ```dart
149
/// const ColoredBox(
150
///   color: Colors.green,
151
///   child: Material(
152
///     child: ListTile(
153
///       title: Text('ListTile with red background'),
154 155 156 157 158
///       tileColor: Colors.red,
///     ),
///   ),
/// )
/// ```
159 160 161 162 163 164 165
/// {@end-tool}
///
/// ## Performance considerations when wrapping [ListTile] with [Material]
///
/// Wrapping a large number of [ListTile]s individually with [Material]s
/// is expensive. Consider only wrapping the [ListTile]s that require it
/// or include a common [Material] ancestor where possible.
166
///
167 168 169 170 171 172 173 174 175 176
/// [ListTile] must be wrapped in a [Material] widget to animate [tileColor],
/// [selectedTileColor], [focusColor], and [hoverColor] as these colors
/// are not drawn by the list tile itself but by the material widget ancestor.
///
/// {@tool dartpad}
/// This example showcases how [ListTile] needs to be wrapped in a [Material]
/// widget to animate colors.
///
/// ** See code in examples/api/lib/material/list_tile/list_tile.0.dart **
/// {@end-tool}
177
///
178
/// {@tool dartpad}
179 180 181 182
/// 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)
183
///
184
/// ** See code in examples/api/lib/material/list_tile/list_tile.1.dart **
185
/// {@end-tool}
186
///
187 188 189 190 191 192
/// {@tool dartpad}
/// This sample shows the creation of a [ListTile] using [ThemeData.useMaterial3] flag,
/// as described in: https://m3.material.io/components/lists/overview.
///
/// ** See code in examples/api/lib/material/list_tile/list_tile.2.dart **
/// {@end-tool}
193
///
194 195 196 197 198 199 200 201
/// {@tool dartpad}
/// This sample shows [ListTile]'s [textColor] and [iconColor] can use
/// [MaterialStateColor] color to change the color of the text and icon
/// when the [ListTile] is enabled, selected, or disabled.
///
/// ** See code in examples/api/lib/material/list_tile/list_tile.3.dart **
/// {@end-tool}
///
202 203 204 205 206 207 208 209
/// {@tool dartpad}
/// This sample shows [ListTile.titleAlignment] can be used to configure the
/// [leading] and [trailing] widgets alignment relative to the [title] and
/// [subtitle] widgets.
///
/// ** See code in examples/api/lib/material/list_tile/list_tile.4.dart **
/// {@end-tool}
///
210
/// {@tool snippet}
Aayan's avatar
Aayan committed
211 212 213 214 215
/// 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
216 217
/// const Row(
///   children: <Widget>[
Aayan's avatar
Aayan committed
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
///     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}
///
236 237 238 239 240
/// 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
241
/// ListTile(
242
///   leading: const Icon(Icons.flight_land),
243
///   title: const Text("Trix's airplane"),
244 245 246 247 248
///   subtitle: _act != 2 ? const Text('The airplane is only in Act II.') : null,
///   enabled: _act == 2,
///   onTap: () { /* react to the tile being tapped */ }
/// )
/// ```
249
/// {@end-tool}
250
///
251 252 253 254 255 256 257 258 259 260 261 262
/// 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.
///
263
/// {@tool snippet}
264 265
///
/// Here is an example of a one-line, non-[dense] ListTile with a
266 267 268 269 270 271 272 273 274 275 276 277
/// 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,
278
///       padding: const EdgeInsets.symmetric(vertical: 4.0),
279
///       alignment: Alignment.center,
280
///       child: const CircleAvatar(),
281 282
///     ),
///   ),
283
///   title: const Text('title'),
284
///   dense: false,
285
/// )
286 287 288
/// ```
/// {@end-tool}
///
289 290 291 292 293 294
/// ## 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.
///
295
/// {@tool dartpad}
296
/// Here is an example of a custom list item that resembles a YouTube-related
297 298
/// video list item created with [Expanded] and [Container] widgets.
///
299
/// ** See code in examples/api/lib/material/list_tile/custom_list_item.0.dart **
300 301
/// {@end-tool}
///
302
/// {@tool dartpad}
303
/// Here is an example of an article list item with multiline titles and
304 305 306
/// subtitles. It utilizes [Row]s and [Column]s, as well as [Expanded] and
/// [AspectRatio] widgets to organize its layout.
///
307
/// ** See code in examples/api/lib/material/list_tile/custom_list_item.1.dart **
308 309
/// {@end-tool}
///
310
/// See also:
311
///
312
///  * [ListTileTheme], which defines visual properties for [ListTile]s.
313 314 315 316
///  * [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.
317
///  * [Card], which can be used with [Column] to show a few [ListTile]s.
318
///  * [Divider], which can be used to separate [ListTile]s.
319
///  * [ListTile.divideTiles], a utility for inserting [Divider]s in between [ListTile]s.
320 321
///  * [CheckboxListTile], [RadioListTile], and [SwitchListTile], widgets
///    that combine [ListTile] with other controls.
322 323
///  * Material 3 [ListTile] specifications are referenced from <https://m3.material.io/components/lists/specs>
///    and Material 2 [ListTile] specifications are referenced from <https://material.io/design/components/lists.html>
324 325
///  * Cookbook: [Use lists](https://flutter.dev/docs/cookbook/lists/basic-list)
///  * Cookbook: [Implement swipe to dismiss](https://flutter.dev/docs/cookbook/gestures/dismissible)
326 327
class ListTile extends StatelessWidget {
  /// Creates a list tile.
328 329 330 331
  ///
  /// If [isThreeLine] is true, then [subtitle] must not be null.
  ///
  /// Requires one of its ancestors to be a [Material] widget.
332
  const ListTile({
333
    super.key,
334 335 336 337
    this.leading,
    this.title,
    this.subtitle,
    this.trailing,
338
    this.isThreeLine = false,
339
    this.dense,
340
    this.visualDensity,
341
    this.shape,
342 343 344 345
    this.style,
    this.selectedColor,
    this.iconColor,
    this.textColor,
346 347 348
    this.titleTextStyle,
    this.subtitleTextStyle,
    this.leadingAndTrailingTextStyle,
349
    this.contentPadding,
350
    this.enabled = true,
Adam Barth's avatar
Adam Barth committed
351
    this.onTap,
352
    this.onLongPress,
353
    this.onFocusChange,
354
    this.mouseCursor,
355
    this.selected = false,
356 357
    this.focusColor,
    this.hoverColor,
358
    this.splashColor,
359
    this.focusNode,
360
    this.autofocus = false,
361 362
    this.tileColor,
    this.selectedTileColor,
363
    this.enableFeedback,
364 365 366
    this.horizontalTitleGap,
    this.minVerticalPadding,
    this.minLeadingWidth,
367
    this.titleAlignment,
368
  }) : assert(!isThreeLine || subtitle != null);
Adam Barth's avatar
Adam Barth committed
369

370 371
  /// A widget to display before the title.
  ///
372
  /// Typically an [Icon] or a [CircleAvatar] widget.
373
  final Widget? leading;
374

375
  /// The primary content of the list tile.
376 377
  ///
  /// Typically a [Text] widget.
378
  ///
379 380
  /// This should not wrap. To enforce the single line limit, use
  /// [Text.maxLines].
381
  final Widget? title;
382 383 384 385

  /// Additional content displayed below the title.
  ///
  /// Typically a [Text] widget.
386 387 388 389
  ///
  /// If [isThreeLine] is false, this should not wrap.
  ///
  /// If [isThreeLine] is true, this should be configured to take a maximum of
390 391
  /// two lines. For example, you can use [Text.maxLines] to enforce the number
  /// of lines.
392
  ///
393
  /// The subtitle's default [TextStyle] depends on [TextTheme.bodyMedium] except
394 395 396 397 398 399
  /// [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]
400
  /// if it's not null and to [TextTheme.bodySmall]'s color if [ListTileTheme.textColor]
401
  /// is null.
402
  final Widget? subtitle;
403 404 405 406

  /// A widget to display after the title.
  ///
  /// Typically an [Icon] widget.
407 408 409
  ///
  /// To show right-aligned metadata (assuming left-to-right reading order;
  /// left-aligned for right-to-left reading order), consider using a [Row] with
410
  /// [CrossAxisAlignment.baseline] alignment whose first item is [Expanded] and
411 412
  /// whose second child is the metadata text, instead of using the [trailing]
  /// property.
413
  final Widget? trailing;
414

415
  /// Whether this list tile is intended to display three lines of text.
416
  ///
417 418 419
  /// If true, then [subtitle] must be non-null (since it is expected to give
  /// the second and third lines of text).
  ///
420
  /// If false, the list tile is treated as having one line if the subtitle is
421
  /// null and treated as having two lines if the subtitle is non-null.
422 423 424
  ///
  /// When using a [Text] widget for [title] and [subtitle], you can enforce
  /// line limits using [Text.maxLines].
Hans Muller's avatar
Hans Muller committed
425
  final bool isThreeLine;
426

427
  /// {@template flutter.material.ListTile.dense}
428
  /// Whether this list tile is part of a vertically dense list.
429 430
  ///
  /// If this property is null then its value is based on [ListTileTheme.dense].
431 432
  ///
  /// Dense list tiles default to a smaller height.
433 434
  ///
  /// It is not recommended to set [dense] to true when [ThemeData.useMaterial3] is true.
435
  /// {@endtemplate}
436
  final bool? dense;
437

438 439 440 441 442 443
  /// Defines how compact the list tile's layout will be.
  ///
  /// {@macro flutter.material.themedata.visualDensity}
  ///
  /// See also:
  ///
444 445
  ///  * [ThemeData.visualDensity], which specifies the [visualDensity] for all
  ///    widgets within a [Theme].
446
  final VisualDensity? visualDensity;
447

448
  /// {@template flutter.material.ListTile.shape}
449
  /// Defines the tile's [InkWell.customBorder] and [Ink.decoration] shape.
450 451 452 453 454 455
  /// {@endtemplate}
  ///
  /// If this property is null then [ListTileThemeData.shape] is used. If that
  /// is also null then a rectangular [Border] will be used.
  ///
  /// See also:
456
  ///
457 458
  /// * [ListTileTheme.of], which returns the nearest [ListTileTheme]'s
  ///   [ListTileThemeData].
459
  final ShapeBorder? shape;
460

461 462 463 464 465 466 467 468 469 470 471 472 473
  /// Defines the color used for icons and text when the list tile is selected.
  ///
  /// If this property is null then [ListTileThemeData.selectedColor]
  /// is used. If that is also null then [ColorScheme.primary] is used.
  ///
  /// See also:
  ///
  /// * [ListTileTheme.of], which returns the nearest [ListTileTheme]'s
  ///   [ListTileThemeData].
  final Color? selectedColor;

  /// Defines the default color for [leading] and [trailing] icons.
  ///
474
  /// If this property is null and [selected] is false then [ListTileThemeData.iconColor]
475
  /// is used. If that is also null and [ThemeData.useMaterial3] is true, [ColorScheme.onSurfaceVariant]
476 477 478 479 480 481 482 483
  /// is used, otherwise if [ThemeData.brightness] is [Brightness.light], [Colors.black54] is used,
  /// and if [ThemeData.brightness] is [Brightness.dark], the value is null.
  ///
  /// If this property is null and [selected] is true then [ListTileThemeData.selectedColor]
  /// is used. If that is also null then [ColorScheme.primary] is used.
  ///
  /// If this color is a [MaterialStateColor] it will be resolved against
  /// [MaterialState.selected] and [MaterialState.disabled] states.
484 485 486 487 488 489 490
  ///
  /// See also:
  ///
  /// * [ListTileTheme.of], which returns the nearest [ListTileTheme]'s
  ///   [ListTileThemeData].
  final Color? iconColor;

491 492 493 494 495 496 497 498 499
  /// Defines the text color for the [title], [subtitle], [leading], and [trailing].
  ///
  /// If this property is null and [selected] is false then [ListTileThemeData.textColor]
  /// is used. If that is also null then default text color is used for the [title], [subtitle]
  /// [leading], and [trailing]. Except for [subtitle], if [ThemeData.useMaterial3] is false,
  /// [TextTheme.bodySmall] is used.
  ///
  /// If this property is null and [selected] is true then [ListTileThemeData.selectedColor]
  /// is used. If that is also null then [ColorScheme.primary] is used.
500
  ///
501 502
  /// If this color is a [MaterialStateColor] it will be resolved against
  /// [MaterialState.selected] and [MaterialState.disabled] states.
503 504 505 506 507 508 509
  ///
  /// See also:
  ///
  /// * [ListTileTheme.of], which returns the nearest [ListTileTheme]'s
  ///   [ListTileThemeData].
  final Color? textColor;

510 511 512 513
  /// The text style for ListTile's [title].
  ///
  /// If this property is null, then [ListTileThemeData.titleTextStyle] is used.
  /// If that is also null and [ThemeData.useMaterial3] is true, [TextTheme.bodyLarge]
514 515 516
  /// with [ColorScheme.onSurface] will be used. Otherwise, If ListTile style is
  /// [ListTileStyle.list], [TextTheme.titleMedium] will be used and if ListTile style
  /// is [ListTileStyle.drawer], [TextTheme.bodyLarge] will be used.
517 518 519 520 521
  final TextStyle? titleTextStyle;

  /// The text style for ListTile's [subtitle].
  ///
  /// If this property is null, then [ListTileThemeData.subtitleTextStyle] is used.
522 523 524
  /// If that is also null and [ThemeData.useMaterial3] is true, [TextTheme.bodyMedium]
  /// with [ColorScheme.onSurfaceVariant] will be used, otherwise [TextTheme.bodyMedium]
  /// with [TextTheme.bodySmall] color will be used.
525 526 527 528 529 530
  final TextStyle? subtitleTextStyle;

  /// The text style for ListTile's [leading] and [trailing].
  ///
  /// If this property is null, then [ListTileThemeData.leadingAndTrailingTextStyle] is used.
  /// If that is also null and [ThemeData.useMaterial3] is true, [TextTheme.labelSmall]
531 532
  /// with [ColorScheme.onSurfaceVariant] will be used, otherwise [TextTheme.bodyMedium]
  /// will be used.
533 534
  final TextStyle? leadingAndTrailingTextStyle;

535 536 537 538 539 540 541 542 543 544 545
  /// Defines the font used for the [title].
  ///
  /// If this property is null then [ListTileThemeData.style] is used. If that
  /// is also null then [ListTileStyle.list] is used.
  ///
  /// See also:
  ///
  /// * [ListTileTheme.of], which returns the nearest [ListTileTheme]'s
  ///   [ListTileThemeData].
  final ListTileStyle? style;

546 547 548 549 550 551
  /// 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.
552
  final EdgeInsetsGeometry? contentPadding;
553

554
  /// Whether this list tile is interactive.
555
  ///
556
  /// If false, this list tile is styled with the disabled color from the
557 558
  /// current [Theme] and the [onTap] and [onLongPress] callbacks are
  /// inoperative.
559
  final bool enabled;
560

561
  /// Called when the user taps this list tile.
562 563
  ///
  /// Inoperative if [enabled] is false.
564
  final GestureTapCallback? onTap;
565

566
  /// Called when the user long-presses on this list tile.
567 568
  ///
  /// Inoperative if [enabled] is false.
569
  final GestureLongPressCallback? onLongPress;
Adam Barth's avatar
Adam Barth committed
570

571 572 573
  /// {@macro flutter.material.inkwell.onFocusChange}
  final ValueChanged<bool>? onFocusChange;

574
  /// {@template flutter.material.ListTile.mouseCursor}
575 576 577 578 579 580 581 582
  /// 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].
583
  /// {@endtemplate}
584
  ///
585 586 587 588 589 590 591
  /// If null, then the value of [ListTileThemeData.mouseCursor] is used. If
  /// that is also null, then [MaterialStateMouseCursor.clickable] is used.
  ///
  /// See also:
  ///
  ///  * [MaterialStateMouseCursor], which can be used to create a [MouseCursor]
  ///    that is also a [MaterialStateProperty<MouseCursor>].
592
  final MouseCursor? mouseCursor;
593

594 595 596 597
  /// 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].
598
  ///
599
  /// {@tool dartpad}
600
  /// Here is an example of using a [StatefulWidget] to keep track of the
601
  /// selected index, and using that to set the [selected] property on the
602 603
  /// corresponding [ListTile].
  ///
604
  /// ** See code in examples/api/lib/material/list_tile/list_tile.selected.0.dart **
605
  /// {@end-tool}
606 607
  final bool selected;

608
  /// The color for the tile's [Material] when it has the input focus.
609
  final Color? focusColor;
610 611

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

614 615 616
  /// The color of splash for the tile's [Material].
  final Color? splashColor;

617
  /// {@macro flutter.widgets.Focus.focusNode}
618
  final FocusNode? focusNode;
619

620 621 622
  /// {@macro flutter.widgets.Focus.autofocus}
  final bool autofocus;

623
  /// {@template flutter.material.ListTile.tileColor}
624
  /// Defines the background color of `ListTile` when [selected] is false.
625
  ///
626 627 628 629 630
  /// If this property is null and [selected] is false then [ListTileThemeData.tileColor]
  /// is used. If that is also null and [selected] is true, [selectedTileColor] is used.
  /// When that is also null, the [ListTileTheme.selectedTileColor] is used, otherwise
  /// [Colors.transparent] is used.
  ///
631
  /// {@endtemplate}
632
  final Color? tileColor;
633 634 635

  /// Defines the background color of `ListTile` when [selected] is true.
  ///
636
  /// When the value if null, the [selectedTileColor] is set to [ListTileTheme.selectedTileColor]
637
  /// if it's not null and to [Colors.transparent] if it's null.
638
  final Color? selectedTileColor;
639

640
  /// {@template flutter.material.ListTile.enableFeedback}
641 642 643 644 645
  /// 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.
  ///
646 647 648
  /// When null, the default value is true.
  /// {@endtemplate}
  ///
649 650 651 652 653
  /// See also:
  ///
  ///  * [Feedback] for providing platform-specific feedback to certain actions.
  final bool? enableFeedback;

654
  /// The horizontal gap between the titles and the leading/trailing widgets.
655 656 657 658
  ///
  /// 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;
659 660

  /// The minimum padding on the top and bottom of the title and subtitle widgets.
661 662 663 664
  ///
  /// 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;
665

666 667 668 669 670
  /// 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;
671

672 673 674 675 676 677 678 679 680 681 682 683 684 685
  /// Defines how [ListTile.leading] and [ListTile.trailing] are
  /// vertically aligned relative to the [ListTile]'s titles
  /// ([ListTile.title] and [ListTile.subtitle]).
  ///
  /// If this property is null then [ListTileThemeData.titleAlignment]
  /// is used. If that is also null then [ListTileTitleAlignment.threeLine]
  /// is used.
  ///
  /// See also:
  ///
  /// * [ListTileTheme.of], which returns the nearest [ListTileTheme]'s
  ///   [ListTileThemeData].
  final ListTileTitleAlignment? titleAlignment;

686
  /// Add a one pixel border in between each tile. If color isn't specified the
687 688 689 690
  /// [ThemeData.dividerColor] of the context's [Theme] is used.
  ///
  /// See also:
  ///
691
  ///  * [Divider], which you can use to obtain this effect manually.
692
  static Iterable<Widget> divideTiles({ BuildContext? context, required Iterable<Widget> tiles, Color? color }) {
Hans Muller's avatar
Hans Muller committed
693
    assert(color != null || context != null);
694
    tiles = tiles.toList();
Hans Muller's avatar
Hans Muller committed
695

696 697 698
    if (tiles.isEmpty || tiles.length == 1) {
      return tiles;
    }
699

700 701
    Widget wrapTile(Widget tile) {
      return DecoratedBox(
702
        position: DecorationPosition.foreground,
703 704 705 706 707
        decoration: BoxDecoration(
          border: Border(
            bottom: Divider.createBorderSide(context, color: color),
          ),
        ),
708
        child: tile,
Hans Muller's avatar
Hans Muller committed
709 710
      );
    }
711 712 713 714 715

    return <Widget>[
      ...tiles.take(tiles.length - 1).map(wrapTile),
      tiles.last,
    ];
Hans Muller's avatar
Hans Muller committed
716 717
  }

718
  bool _isDenseLayout(ThemeData theme, ListTileThemeData tileTheme) {
719 720 721
    return dense ?? tileTheme.dense ?? theme.listTileTheme.dense ?? false;
  }

722
  Color _tileBackgroundColor(ThemeData theme, ListTileThemeData tileTheme, ListTileThemeData defaults) {
723 724 725
    final Color? color = selected
      ? selectedTileColor ?? tileTheme.selectedTileColor ?? theme.listTileTheme.selectedTileColor
      : tileColor ?? tileTheme.tileColor ?? theme.listTileTheme.tileColor;
726
    return color ?? defaults.tileColor!;
727 728
  }

729
  @override
Adam Barth's avatar
Adam Barth committed
730
  Widget build(BuildContext context) {
731
    assert(debugCheckHasMaterial(context));
732
    final ThemeData theme = Theme.of(context);
733
    final ListTileThemeData tileTheme = ListTileTheme.of(context);
734 735 736 737 738 739 740 741 742 743 744
    final ListTileStyle listTileStyle = style
      ?? tileTheme.style
      ?? theme.listTileTheme.style
      ?? ListTileStyle.list;
    final ListTileThemeData defaults = theme.useMaterial3
        ? _LisTileDefaultsM3(context)
        : _LisTileDefaultsM2(context, listTileStyle);
    final Set<MaterialState> states = <MaterialState>{
      if (!enabled) MaterialState.disabled,
      if (selected) MaterialState.selected,
    };
745

746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
    Color? resolveColor(Color? explicitColor, Color? selectedColor, Color? enabledColor, [Color? disabledColor]) {
      return _IndividualOverrides(
        explicitColor: explicitColor,
        selectedColor: selectedColor,
        enabledColor: enabledColor,
        disabledColor: disabledColor,
      ).resolve(states);
    }

    final Color? effectiveIconColor = resolveColor(iconColor, selectedColor, iconColor)
      ?? resolveColor(tileTheme.iconColor, tileTheme.selectedColor, tileTheme.iconColor)
      ?? resolveColor(theme.listTileTheme.iconColor, theme.listTileTheme.selectedColor, theme.listTileTheme.iconColor)
      ?? resolveColor(defaults.iconColor, defaults.selectedColor, defaults.iconColor, theme.disabledColor);
    final Color? effectiveColor = resolveColor(textColor, selectedColor, textColor)
      ?? resolveColor(tileTheme.textColor, tileTheme.selectedColor, tileTheme.textColor)
      ?? resolveColor(theme.listTileTheme.textColor, theme.listTileTheme.selectedColor, theme.listTileTheme.textColor)
      ?? resolveColor(defaults.textColor, defaults.selectedColor, defaults.textColor, theme.disabledColor);
    final IconThemeData iconThemeData = IconThemeData(color: effectiveIconColor);
764 765 766
    final IconButtonThemeData iconButtonThemeData = IconButtonThemeData(
      style: IconButton.styleFrom(foregroundColor: effectiveIconColor),
    );
767 768

    TextStyle? leadingAndTrailingStyle;
769
    if (leading != null || trailing != null) {
770 771 772 773 774
      leadingAndTrailingStyle = leadingAndTrailingTextStyle
        ?? tileTheme.leadingAndTrailingTextStyle
        ?? defaults.leadingAndTrailingTextStyle!;
      final Color? leadingAndTrailingTextColor = effectiveColor;
      leadingAndTrailingStyle = leadingAndTrailingStyle.copyWith(color: leadingAndTrailingTextColor);
775
    }
776

777
    Widget? leadingIcon;
778
    if (leading != null) {
779
      leadingIcon = AnimatedDefaultTextStyle(
780
        style: leadingAndTrailingStyle!,
781
        duration: kThemeChangeDuration,
782
        child: leading!,
783
      );
Adam Barth's avatar
Adam Barth committed
784 785
    }

786 787 788 789 790 791 792 793
    TextStyle titleStyle = titleTextStyle
      ?? tileTheme.titleTextStyle
      ?? defaults.titleTextStyle!;
    final Color? titleColor = effectiveColor;
    titleStyle = titleStyle.copyWith(
      color: titleColor,
      fontSize: _isDenseLayout(theme, tileTheme) ? 13.0 : null,
    );
794
    final Widget titleText = AnimatedDefaultTextStyle(
795
      style: titleStyle,
796
      duration: kThemeChangeDuration,
797
      child: title ?? const SizedBox(),
Hans Muller's avatar
Hans Muller committed
798
    );
799

800 801
    Widget? subtitleText;
    TextStyle? subtitleStyle;
802
    if (subtitle != null) {
803 804 805
      subtitleStyle = subtitleTextStyle
        ?? tileTheme.subtitleTextStyle
        ?? defaults.subtitleTextStyle!;
806
      final Color? subtitleColor = effectiveColor;
807 808 809 810
      subtitleStyle = subtitleStyle.copyWith(
        color: subtitleColor,
        fontSize: _isDenseLayout(theme, tileTheme) ? 12.0 : null,
      );
811
      subtitleText = AnimatedDefaultTextStyle(
812
        style: subtitleStyle,
813
        duration: kThemeChangeDuration,
814
        child: subtitle!,
Hans Muller's avatar
Hans Muller committed
815 816
      );
    }
Adam Barth's avatar
Adam Barth committed
817

818
    Widget? trailingIcon;
819
    if (trailing != null) {
820
      trailingIcon = AnimatedDefaultTextStyle(
821
        style: leadingAndTrailingStyle!,
822
        duration: kThemeChangeDuration,
823
        child: trailing!,
824
      );
Adam Barth's avatar
Adam Barth committed
825 826
    }

827
    final TextDirection textDirection = Directionality.of(context);
828
    final EdgeInsets resolvedContentPadding = contentPadding?.resolve(textDirection)
829
      ?? tileTheme.contentPadding?.resolve(textDirection)
830
      ?? defaults.contentPadding!.resolve(textDirection);
831

832 833
    // Show basic cursor when ListTile isn't enabled or gesture callbacks are null.
    final Set<MaterialState> mouseStates = <MaterialState>{
834 835
      if (!enabled || (onTap == null && onLongPress == null)) MaterialState.disabled,
    };
836 837 838
    final MouseCursor effectiveMouseCursor = MaterialStateProperty.resolveAs<MouseCursor?>(mouseCursor, mouseStates)
      ?? tileTheme.mouseCursor?.resolve(mouseStates)
      ?? MaterialStateMouseCursor.clickable.resolve(mouseStates);
839

840 841 842 843
    final ListTileTitleAlignment effectiveTitleAlignment = titleAlignment
      ?? tileTheme.titleAlignment
      ?? (theme.useMaterial3 ? ListTileTitleAlignment.threeLine : ListTileTitleAlignment.titleHeight);

844
    return InkWell(
845
      customBorder: shape ?? tileTheme.shape,
846 847
      onTap: enabled ? onTap : null,
      onLongPress: enabled ? onLongPress : null,
848
      onFocusChange: onFocusChange,
849
      mouseCursor: effectiveMouseCursor,
850
      canRequestFocus: enabled,
851 852 853
      focusNode: focusNode,
      focusColor: focusColor,
      hoverColor: hoverColor,
854
      splashColor: splashColor,
855
      autofocus: autofocus,
856
      enableFeedback: enableFeedback ?? tileTheme.enableFeedback ?? true,
857
      child: Semantics(
858
        selected: selected,
859
        enabled: enabled,
860 861 862
        child: Ink(
          decoration: ShapeDecoration(
            shape: shape ?? tileTheme.shape ?? const Border(),
863
            color: _tileBackgroundColor(theme, tileTheme, defaults),
864
          ),
865 866 867 868
          child: SafeArea(
            top: false,
            bottom: false,
            minimum: resolvedContentPadding,
869 870
            child: IconTheme.merge(
              data: iconThemeData,
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
              child: IconButtonTheme(
                data: iconButtonThemeData,
                child: _ListTile(
                  leading: leadingIcon,
                  title: titleText,
                  subtitle: subtitleText,
                  trailing: trailingIcon,
                  isDense: _isDenseLayout(theme, tileTheme),
                  visualDensity: visualDensity ?? tileTheme.visualDensity ?? theme.visualDensity,
                  isThreeLine: isThreeLine,
                  textDirection: textDirection,
                  titleBaselineType: titleStyle.textBaseline ?? defaults.titleTextStyle!.textBaseline!,
                  subtitleBaselineType: subtitleStyle?.textBaseline ?? defaults.subtitleTextStyle!.textBaseline!,
                  horizontalTitleGap: horizontalTitleGap ?? tileTheme.horizontalTitleGap ?? 16,
                  minVerticalPadding: minVerticalPadding ?? tileTheme.minVerticalPadding ?? defaults.minVerticalPadding!,
                  minLeadingWidth: minLeadingWidth ?? tileTheme.minLeadingWidth ?? defaults.minLeadingWidth!,
887
                  titleAlignment: effectiveTitleAlignment,
888
                ),
889
              ),
890
            ),
891
          ),
892
       ),
893
      ),
Adam Barth's avatar
Adam Barth committed
894 895
    );
  }
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(DiagnosticsProperty<Widget>('leading', leading, defaultValue: null));
    properties.add(DiagnosticsProperty<Widget>('title', title, defaultValue: null));
    properties.add(DiagnosticsProperty<Widget>('subtitle', subtitle, defaultValue: null));
    properties.add(DiagnosticsProperty<Widget>('trailing', trailing, defaultValue: null));
    properties.add(FlagProperty('isThreeLine', value: isThreeLine, ifTrue:'THREE_LINE', ifFalse: 'TWO_LINE', showName: true, defaultValue: false));
    properties.add(FlagProperty('dense', value: dense, ifTrue: 'true', ifFalse: 'false', showName: true));
    properties.add(DiagnosticsProperty<VisualDensity>('visualDensity', visualDensity, defaultValue: null));
    properties.add(DiagnosticsProperty<ShapeBorder>('shape', shape, defaultValue: null));
    properties.add(DiagnosticsProperty<ListTileStyle>('style', style, defaultValue: null));
    properties.add(ColorProperty('selectedColor', selectedColor, defaultValue: null));
    properties.add(ColorProperty('iconColor', iconColor, defaultValue: null));
    properties.add(ColorProperty('textColor', textColor, defaultValue: null));
912 913 914
    properties.add(DiagnosticsProperty<TextStyle>('titleTextStyle', titleTextStyle, defaultValue: null));
    properties.add(DiagnosticsProperty<TextStyle>('subtitleTextStyle', subtitleTextStyle, defaultValue: null));
    properties.add(DiagnosticsProperty<TextStyle>('leadingAndTrailingTextStyle', leadingAndTrailingTextStyle, defaultValue: null));
915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930
    properties.add(DiagnosticsProperty<EdgeInsetsGeometry>('contentPadding', contentPadding, defaultValue: null));
    properties.add(FlagProperty('enabled', value: enabled, ifTrue: 'true', ifFalse: 'false', showName: true, defaultValue: true));
    properties.add(DiagnosticsProperty<Function>('onTap', onTap, defaultValue: null));
    properties.add(DiagnosticsProperty<Function>('onLongPress', onLongPress, defaultValue: null));
    properties.add(DiagnosticsProperty<MouseCursor>('mouseCursor', mouseCursor, defaultValue: null));
    properties.add(FlagProperty('selected', value: selected, ifTrue: 'true', ifFalse: 'false', showName: true, defaultValue: false));
    properties.add(ColorProperty('focusColor', focusColor, defaultValue: null));
    properties.add(ColorProperty('hoverColor', hoverColor, defaultValue: null));
    properties.add(DiagnosticsProperty<FocusNode>('focusNode', focusNode, defaultValue: null));
    properties.add(FlagProperty('autofocus', value: autofocus, ifTrue: 'true', ifFalse: 'false', showName: true, defaultValue: false));
    properties.add(ColorProperty('tileColor', tileColor, defaultValue: null));
    properties.add(ColorProperty('selectedTileColor', selectedTileColor, defaultValue: null));
    properties.add(FlagProperty('enableFeedback', value: enableFeedback, ifTrue: 'true', ifFalse: 'false', showName: true));
    properties.add(DoubleProperty('horizontalTitleGap', horizontalTitleGap, defaultValue: null));
    properties.add(DoubleProperty('minVerticalPadding', minVerticalPadding, defaultValue: null));
    properties.add(DoubleProperty('minLeadingWidth', minLeadingWidth, defaultValue: null));
931
    properties.add(DiagnosticsProperty<ListTileTitleAlignment>('titleAlignment', titleAlignment, defaultValue: null));
932
  }
Adam Barth's avatar
Adam Barth committed
933
}
934

935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962
class _IndividualOverrides extends MaterialStateProperty<Color?> {
  _IndividualOverrides({
    this.explicitColor,
    this.enabledColor,
    this.selectedColor,
    this.disabledColor,
  });

  final Color? explicitColor;
  final Color? enabledColor;
  final Color? selectedColor;
  final Color? disabledColor;

  @override
  Color? resolve(Set<MaterialState> states) {
    if (explicitColor is MaterialStateColor) {
      return MaterialStateProperty.resolveAs<Color?>(explicitColor, states);
    }
    if (states.contains(MaterialState.disabled)) {
      return disabledColor;
    }
    if (states.contains(MaterialState.selected)) {
      return selectedColor;
    }
    return enabledColor;
  }
}

963 964 965 966 967 968 969 970
// Identifies the children of a _ListTileElement.
enum _ListTileSlot {
  leading,
  title,
  subtitle,
  trailing,
}

971
class _ListTile extends SlottedMultiChildRenderObjectWidget<_ListTileSlot, RenderBox> {
972 973
  const _ListTile({
    this.leading,
974
    required this.title,
975 976
    this.subtitle,
    this.trailing,
977 978 979 980 981
    required this.isThreeLine,
    required this.isDense,
    required this.visualDensity,
    required this.textDirection,
    required this.titleBaselineType,
982 983 984
    required this.horizontalTitleGap,
    required this.minVerticalPadding,
    required this.minLeadingWidth,
985
    this.subtitleBaselineType,
986
    required this.titleAlignment,
987
  });
988

989
  final Widget? leading;
990
  final Widget title;
991 992
  final Widget? subtitle;
  final Widget? trailing;
993 994
  final bool isThreeLine;
  final bool isDense;
995
  final VisualDensity visualDensity;
996 997
  final TextDirection textDirection;
  final TextBaseline titleBaselineType;
998
  final TextBaseline? subtitleBaselineType;
999 1000 1001
  final double horizontalTitleGap;
  final double minVerticalPadding;
  final double minLeadingWidth;
1002
  final ListTileTitleAlignment titleAlignment;
1003 1004

  @override
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
  Iterable<_ListTileSlot> get slots => _ListTileSlot.values;

  @override
  Widget? childForSlot(_ListTileSlot slot) {
    switch (slot) {
      case _ListTileSlot.leading:
        return leading;
      case _ListTileSlot.title:
        return title;
      case _ListTileSlot.subtitle:
        return subtitle;
      case _ListTileSlot.trailing:
        return trailing;
    }
  }
1020 1021 1022

  @override
  _RenderListTile createRenderObject(BuildContext context) {
1023
    return _RenderListTile(
1024 1025
      isThreeLine: isThreeLine,
      isDense: isDense,
1026
      visualDensity: visualDensity,
1027 1028 1029
      textDirection: textDirection,
      titleBaselineType: titleBaselineType,
      subtitleBaselineType: subtitleBaselineType,
1030 1031 1032
      horizontalTitleGap: horizontalTitleGap,
      minVerticalPadding: minVerticalPadding,
      minLeadingWidth: minLeadingWidth,
1033
      titleAlignment: titleAlignment,
1034 1035 1036 1037 1038 1039 1040 1041
    );
  }

  @override
  void updateRenderObject(BuildContext context, _RenderListTile renderObject) {
    renderObject
      ..isThreeLine = isThreeLine
      ..isDense = isDense
1042
      ..visualDensity = visualDensity
1043 1044
      ..textDirection = textDirection
      ..titleBaselineType = titleBaselineType
1045 1046 1047
      ..subtitleBaselineType = subtitleBaselineType
      ..horizontalTitleGap = horizontalTitleGap
      ..minLeadingWidth = minLeadingWidth
1048
      ..minVerticalPadding = minVerticalPadding
1049
      ..titleAlignment = titleAlignment;
1050 1051 1052
  }
}

1053
class _RenderListTile extends RenderBox with SlottedContainerRenderObjectMixin<_ListTileSlot, RenderBox> {
1054
  _RenderListTile({
1055 1056 1057 1058 1059 1060
    required bool isDense,
    required VisualDensity visualDensity,
    required bool isThreeLine,
    required TextDirection textDirection,
    required TextBaseline titleBaselineType,
    TextBaseline? subtitleBaselineType,
1061 1062 1063
    required double horizontalTitleGap,
    required double minVerticalPadding,
    required double minLeadingWidth,
1064
    required ListTileTitleAlignment titleAlignment,
1065
  }) : _isDense = isDense,
1066
       _visualDensity = visualDensity,
1067
       _isThreeLine = isThreeLine,
1068 1069
       _textDirection = textDirection,
       _titleBaselineType = titleBaselineType,
1070
       _subtitleBaselineType = subtitleBaselineType,
1071
       _horizontalTitleGap = horizontalTitleGap,
1072
       _minVerticalPadding = minVerticalPadding,
1073
       _minLeadingWidth = minLeadingWidth,
1074
       _titleAlignment = titleAlignment;
1075

1076 1077 1078 1079
  RenderBox? get leading => childForSlot(_ListTileSlot.leading);
  RenderBox? get title => childForSlot(_ListTileSlot.title);
  RenderBox? get subtitle => childForSlot(_ListTileSlot.subtitle);
  RenderBox? get trailing => childForSlot(_ListTileSlot.trailing);
1080 1081

  // The returned list is ordered for hit testing.
1082
  @override
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
  Iterable<RenderBox> get children {
    return <RenderBox>[
      if (leading != null)
        leading!,
      if (title != null)
        title!,
      if (subtitle != null)
        subtitle!,
      if (trailing != null)
        trailing!,
    ];
1094 1095 1096 1097 1098
  }

  bool get isDense => _isDense;
  bool _isDense;
  set isDense(bool value) {
1099
    if (_isDense == value) {
1100
      return;
1101
    }
1102 1103 1104 1105
    _isDense = value;
    markNeedsLayout();
  }

1106 1107 1108
  VisualDensity get visualDensity => _visualDensity;
  VisualDensity _visualDensity;
  set visualDensity(VisualDensity value) {
1109
    if (_visualDensity == value) {
1110
      return;
1111
    }
1112 1113 1114 1115
    _visualDensity = value;
    markNeedsLayout();
  }

1116 1117 1118
  bool get isThreeLine => _isThreeLine;
  bool _isThreeLine;
  set isThreeLine(bool value) {
1119
    if (_isThreeLine == value) {
1120
      return;
1121
    }
1122 1123 1124 1125 1126 1127 1128
    _isThreeLine = value;
    markNeedsLayout();
  }

  TextDirection get textDirection => _textDirection;
  TextDirection _textDirection;
  set textDirection(TextDirection value) {
1129
    if (_textDirection == value) {
1130
      return;
1131
    }
1132 1133 1134 1135
    _textDirection = value;
    markNeedsLayout();
  }

1136 1137 1138
  TextBaseline get titleBaselineType => _titleBaselineType;
  TextBaseline _titleBaselineType;
  set titleBaselineType(TextBaseline value) {
1139
    if (_titleBaselineType == value) {
1140
      return;
1141
    }
1142 1143 1144 1145
    _titleBaselineType = value;
    markNeedsLayout();
  }

1146 1147 1148
  TextBaseline? get subtitleBaselineType => _subtitleBaselineType;
  TextBaseline? _subtitleBaselineType;
  set subtitleBaselineType(TextBaseline? value) {
1149
    if (_subtitleBaselineType == value) {
1150
      return;
1151
    }
1152 1153 1154 1155
    _subtitleBaselineType = value;
    markNeedsLayout();
  }

1156 1157
  double get horizontalTitleGap => _horizontalTitleGap;
  double _horizontalTitleGap;
1158
  double get _effectiveHorizontalTitleGap => _horizontalTitleGap + visualDensity.horizontal * 2.0;
1159 1160

  set horizontalTitleGap(double value) {
1161
    if (_horizontalTitleGap == value) {
1162
      return;
1163
    }
1164 1165 1166 1167 1168 1169 1170 1171
    _horizontalTitleGap = value;
    markNeedsLayout();
  }

  double get minVerticalPadding => _minVerticalPadding;
  double _minVerticalPadding;

  set minVerticalPadding(double value) {
1172
    if (_minVerticalPadding == value) {
1173
      return;
1174
    }
1175 1176 1177 1178 1179 1180 1181 1182
    _minVerticalPadding = value;
    markNeedsLayout();
  }

  double get minLeadingWidth => _minLeadingWidth;
  double _minLeadingWidth;

  set minLeadingWidth(double value) {
1183
    if (_minLeadingWidth == value) {
1184
      return;
1185
    }
1186 1187 1188 1189
    _minLeadingWidth = value;
    markNeedsLayout();
  }

1190 1191 1192 1193
  ListTileTitleAlignment get titleAlignment => _titleAlignment;
  ListTileTitleAlignment _titleAlignment;
  set titleAlignment(ListTileTitleAlignment value) {
    if (_titleAlignment == value) {
1194 1195
      return;
    }
1196
    _titleAlignment = value;
1197 1198 1199
    markNeedsLayout();
  }

1200 1201 1202
  @override
  bool get sizedByParent => false;

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

1207
  static double _maxWidth(RenderBox? box, double height) {
1208 1209 1210 1211 1212 1213
    return box == null ? 0.0 : box.getMaxIntrinsicWidth(height);
  }

  @override
  double computeMinIntrinsicWidth(double height) {
    final double leadingWidth = leading != null
1214
      ? math.max(leading!.getMinIntrinsicWidth(height), _minLeadingWidth) + _effectiveHorizontalTitleGap
1215 1216 1217 1218 1219 1220 1221 1222 1223
      : 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
1224
      ? math.max(leading!.getMaxIntrinsicWidth(height), _minLeadingWidth) + _effectiveHorizontalTitleGap
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
      : 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;

1236
    final Offset baseDensity = visualDensity.baseSizeAdjustment;
1237
    if (isOneLine) {
1238
      return (isDense ? 48.0 : 56.0) + baseDensity.dy;
1239 1240
    }
    if (isTwoLine) {
1241
      return (isDense ? 64.0 : 72.0) + baseDensity.dy;
1242
    }
1243
    return (isDense ? 76.0 : 88.0) + baseDensity.dy;
1244 1245 1246 1247 1248 1249
  }

  @override
  double computeMinIntrinsicHeight(double width) {
    return math.max(
      _defaultTileHeight,
1250
      title!.getMinIntrinsicHeight(width) + (subtitle?.getMinIntrinsicHeight(width) ?? 0.0),
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
    );
  }

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

  @override
  double computeDistanceToActualBaseline(TextBaseline baseline) {
    assert(title != null);
1262 1263
    final BoxParentData parentData = title!.parentData! as BoxParentData;
    return parentData.offset.dy + title!.getDistanceToActualBaseline(baseline)!;
1264 1265
  }

1266
  static double? _boxBaseline(RenderBox box, TextBaseline baseline) {
1267
    return box.getDistanceToBaseline(baseline);
1268 1269
  }

1270
  static Size _layoutBox(RenderBox? box, BoxConstraints constraints) {
1271
    if (box == null) {
1272
      return Size.zero;
1273
    }
1274 1275 1276 1277 1278
    box.layout(constraints, parentUsesSize: true);
    return box.size;
  }

  static void _positionBox(RenderBox box, Offset offset) {
1279
    final BoxParentData parentData = box.parentData! as BoxParentData;
1280 1281 1282
    parentData.offset = offset;
  }

1283 1284 1285
  @override
  Size computeDryLayout(BoxConstraints constraints) {
    assert(debugCannotComputeDryLayout(
1286
      reason: 'Layout requires baseline metrics, which are only available after a full layout.',
1287
    ));
1288
    return Size.zero;
1289 1290
  }

1291 1292 1293 1294
  // All of the dimensions below were taken from the Material Design spec:
  // https://material.io/design/components/lists.html#specs
  @override
  void performLayout() {
1295
    final BoxConstraints constraints = this.constraints;
1296 1297 1298 1299 1300
    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;
1301
    final Offset densityAdjustment = visualDensity.baseSizeAdjustment;
1302 1303 1304 1305 1306 1307 1308

    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.
1309
      maxHeight: (isDense ? 48.0 : 56.0) + densityAdjustment.dy,
1310
    );
1311
    final BoxConstraints looseConstraints = constraints.loosen();
1312
    final BoxConstraints iconConstraints = looseConstraints.enforce(maxIconHeightConstraint);
1313 1314

    final double tileWidth = looseConstraints.maxWidth;
1315 1316
    final Size leadingSize = _layoutBox(leading, iconConstraints);
    final Size trailingSize = _layoutBox(trailing, iconConstraints);
1317
    assert(
1318
      tileWidth != leadingSize.width || tileWidth == 0.0,
1319 1320
      'Leading widget consumes entire tile width. Please use a sized widget, '
      'or consider replacing ListTile with a custom widget '
1321
      '(see https://api.flutter.dev/flutter/material/ListTile-class.html#material.ListTile.4)',
1322 1323
    );
    assert(
1324
      tileWidth != trailingSize.width || tileWidth == 0.0,
1325 1326
      'Trailing widget consumes entire tile width. Please use a sized widget, '
      'or consider replacing ListTile with a custom widget '
1327
      '(see https://api.flutter.dev/flutter/material/ListTile-class.html#material.ListTile.4)',
1328
    );
1329 1330

    final double titleStart = hasLeading
1331
      ? math.max(_minLeadingWidth, leadingSize.width) + _effectiveHorizontalTitleGap
1332
      : 0.0;
1333
    final double adjustedTrailingWidth = hasTrailing
1334
        ? math.max(trailingSize.width + _effectiveHorizontalTitleGap, 32.0)
1335
        : 0.0;
1336
    final BoxConstraints textConstraints = looseConstraints.tighten(
1337
      width: tileWidth - titleStart - adjustedTrailingWidth,
1338 1339 1340 1341
    );
    final Size titleSize = _layoutBox(title, textConstraints);
    final Size subtitleSize = _layoutBox(subtitle, textConstraints);

1342 1343
    double? titleBaseline;
    double? subtitleBaseline;
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
    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);
    }

1354 1355
    final double defaultTileHeight = _defaultTileHeight;

1356 1357
    double tileHeight;
    double titleY;
1358
    double? subtitleY;
1359
    if (!hasSubtitle) {
1360
      tileHeight = math.max(defaultTileHeight, titleSize.height + 2.0 * _minVerticalPadding);
1361 1362
      titleY = (tileHeight - titleSize.height) / 2.0;
    } else {
1363
      assert(subtitleBaselineType != null);
1364 1365
      titleY = titleBaseline! - _boxBaseline(title!, titleBaselineType)!;
      subtitleY = subtitleBaseline! - _boxBaseline(subtitle!, subtitleBaselineType!)! + visualDensity.vertical * 2.0;
1366
      tileHeight = defaultTileHeight;
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387

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

1388 1389
    final double leadingY;
    final double trailingY;
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421

    switch (titleAlignment) {
      case ListTileTitleAlignment.threeLine: {
        if (isThreeLine) {
          leadingY = _minVerticalPadding;
          trailingY = _minVerticalPadding;
        } else {
          leadingY = (tileHeight - leadingSize.height) / 2.0;
          trailingY = (tileHeight - trailingSize.height) / 2.0;
        }
        break;
      }
      case ListTileTitleAlignment.titleHeight: {
        // This attempts to implement the redlines for the vertical position of the
        // leading and trailing icons on the spec page:
        //   https://m2.material.io/components/lists#specs
        // The interpretation for these redlines is as follows:
        //  - 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.
        if (tileHeight > 72.0) {
          leadingY = 16.0;
          trailingY = 16.0;
        } else {
          leadingY = math.min((tileHeight - leadingSize.height) / 2.0, 16.0);
          trailingY = (tileHeight - trailingSize.height) / 2.0;
        }
        break;
      }
      case ListTileTitleAlignment.top: {
1422 1423
        leadingY = _minVerticalPadding;
        trailingY = _minVerticalPadding;
1424 1425 1426
        break;
      }
      case ListTileTitleAlignment.center: {
1427 1428
        leadingY = (tileHeight - leadingSize.height) / 2.0;
        trailingY = (tileHeight - trailingSize.height) / 2.0;
1429
        break;
1430
      }
1431 1432 1433 1434
      case ListTileTitleAlignment.bottom: {
        leadingY = tileHeight - leadingSize.height - _minVerticalPadding;
        trailingY = tileHeight - trailingSize.height - _minVerticalPadding;
        break;
1435
      }
1436
    }
1437 1438 1439

    switch (textDirection) {
      case TextDirection.rtl: {
1440
        if (hasLeading) {
1441
          _positionBox(leading!, Offset(tileWidth - leadingSize.width, leadingY));
1442
        }
1443
        _positionBox(title!, Offset(adjustedTrailingWidth, titleY));
1444
        if (hasSubtitle) {
1445
          _positionBox(subtitle!, Offset(adjustedTrailingWidth, subtitleY!));
1446 1447
        }
        if (hasTrailing) {
1448
          _positionBox(trailing!, Offset(0.0, trailingY));
1449
        }
1450 1451 1452
        break;
      }
      case TextDirection.ltr: {
1453
        if (hasLeading) {
1454
          _positionBox(leading!, Offset(0.0, leadingY));
1455
        }
1456
        _positionBox(title!, Offset(titleStart, titleY));
1457
        if (hasSubtitle) {
1458
          _positionBox(subtitle!, Offset(titleStart, subtitleY!));
1459 1460
        }
        if (hasTrailing) {
1461
          _positionBox(trailing!, Offset(tileWidth - trailingSize.width, trailingY));
1462
        }
1463 1464 1465 1466
        break;
      }
    }

1467
    size = constraints.constrain(Size(tileWidth, tileHeight));
1468 1469 1470 1471 1472 1473
    assert(size.width == constraints.constrainWidth(tileWidth));
    assert(size.height == constraints.constrainHeight(tileHeight));
  }

  @override
  void paint(PaintingContext context, Offset offset) {
1474
    void doPaint(RenderBox? child) {
1475
      if (child != null) {
1476
        final BoxParentData parentData = child.parentData! as BoxParentData;
1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
        context.paintChild(child, parentData.offset + offset);
      }
    }
    doPaint(leading);
    doPaint(title);
    doPaint(subtitle);
    doPaint(trailing);
  }

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

  @override
1490
  bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
1491
    for (final RenderBox child in children) {
1492
      final BoxParentData parentData = child.parentData! as BoxParentData;
1493 1494 1495 1496 1497 1498 1499 1500
      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);
        },
      );
1501
      if (isHit) {
1502
        return true;
1503
      }
1504 1505 1506 1507
    }
    return false;
  }
}
1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536

class _LisTileDefaultsM2 extends ListTileThemeData {
  _LisTileDefaultsM2(this.context, ListTileStyle style)
    : super(
        contentPadding: const EdgeInsets.symmetric(horizontal: 16.0),
        minLeadingWidth: 40,
        minVerticalPadding: 4,
        shape: const Border(),
        style: style,
      );

  final BuildContext context;
  late final ThemeData _theme = Theme.of(context);
  late final TextTheme _textTheme = _theme.textTheme;

  @override
  Color? get tileColor =>  Colors.transparent;

  @override
  TextStyle? get titleTextStyle {
    switch (style!) {
      case ListTileStyle.drawer:
        return _textTheme.bodyLarge;
      case ListTileStyle.list:
        return _textTheme.titleMedium;
    }
  }

  @override
1537 1538
  TextStyle? get subtitleTextStyle => _textTheme.bodyMedium!
    .copyWith(color: _textTheme.bodySmall!.color);
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 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583

  @override
  TextStyle? get leadingAndTrailingTextStyle => _textTheme.bodyMedium;

  @override
  Color? get selectedColor => _theme.colorScheme.primary;

  @override
  Color? get iconColor {
    switch (_theme.brightness) {
      case Brightness.light:
        // For the sake of backwards compatibility, the default for unselected
        // tiles is Colors.black45 rather than colorScheme.onSurface.withAlpha(0x73).
        return Colors.black45;
      case Brightness.dark:
        return null; // null, Use current icon theme color
    }
  }
}

// BEGIN GENERATED TOKEN PROPERTIES - LisTile

// Do not edit by hand. The code between the "BEGIN GENERATED" and
// "END GENERATED" comments are generated from data in the Material
// Design token database by the script:
//   dev/tools/gen_defaults/bin/gen_defaults.dart.

class _LisTileDefaultsM3 extends ListTileThemeData {
  _LisTileDefaultsM3(this.context)
    : super(
        contentPadding: const EdgeInsetsDirectional.only(start: 16.0, end: 24.0),
        minLeadingWidth: 24,
        minVerticalPadding: 8,
        shape: const RoundedRectangleBorder(),
      );

  final BuildContext context;
  late final ThemeData _theme = Theme.of(context);
  late final ColorScheme _colors = _theme.colorScheme;
  late final TextTheme _textTheme = _theme.textTheme;

  @override
  Color? get tileColor =>  Colors.transparent;

  @override
1584
  TextStyle? get titleTextStyle => _textTheme.bodyLarge!.copyWith(color: _colors.onSurface);
1585 1586

  @override
1587
  TextStyle? get subtitleTextStyle => _textTheme.bodyMedium!.copyWith(color: _colors.onSurfaceVariant);
1588 1589

  @override
1590
  TextStyle? get leadingAndTrailingTextStyle => _textTheme.labelSmall!.copyWith(color: _colors.onSurfaceVariant);
1591 1592 1593 1594 1595

  @override
  Color? get selectedColor => _colors.primary;

  @override
1596
  Color? get iconColor => _colors.onSurfaceVariant;
1597 1598 1599
}

// END GENERATED TOKEN PROPERTIES - LisTile