about.dart 48.9 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
Ian Hickson's avatar
Ian Hickson 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
import 'dart:developer' show Flow, Timeline;
6
import 'dart:io' show Platform;
Ian Hickson's avatar
Ian Hickson committed
7

8
import 'package:flutter/foundation.dart';
9 10
import 'package:flutter/scheduler.dart';
import 'package:flutter/widgets.dart' hide Flow;
Ian Hickson's avatar
Ian Hickson committed
11 12

import 'app_bar.dart';
13 14 15
import 'back_button.dart';
import 'card.dart';
import 'constants.dart';
Ian Hickson's avatar
Ian Hickson committed
16 17
import 'debug.dart';
import 'dialog.dart';
18
import 'divider.dart';
19 20
import 'floating_action_button_location.dart';
import 'ink_decoration.dart';
21
import 'list_tile.dart';
22
import 'material.dart';
23
import 'material_localizations.dart';
Ian Hickson's avatar
Ian Hickson committed
24
import 'page.dart';
25
import 'page_transitions_theme.dart';
Ian Hickson's avatar
Ian Hickson committed
26
import 'progress_indicator.dart';
Ian Hickson's avatar
Ian Hickson committed
27
import 'scaffold.dart';
28
import 'scrollbar.dart';
29
import 'text_button.dart';
30
import 'text_theme.dart';
Ian Hickson's avatar
Ian Hickson committed
31 32
import 'theme.dart';

33
/// A [ListTile] that shows an about box.
Ian Hickson's avatar
Ian Hickson committed
34
///
35 36
/// This widget is often added to an app's [Drawer]. When tapped it shows
/// an about box dialog with [showAboutDialog].
Ian Hickson's avatar
Ian Hickson committed
37 38
///
/// The about box will include a button that shows licenses for software used by
39 40
/// the application. The licenses shown are those returned by the
/// [LicenseRegistry] API, which can be used to add more licenses to the list.
Ian Hickson's avatar
Ian Hickson committed
41 42 43
///
/// If your application does not have a [Drawer], you should provide an
/// affordance to call [showAboutDialog] or (at least) [showLicensePage].
44
///
45
/// {@tool dartpad}
46 47 48
/// This sample shows two ways to open [AboutDialog]. The first one
/// uses an [AboutListTile], and the second uses the [showAboutDialog] function.
///
49
/// ** See code in examples/api/lib/material/about/about_list_tile.0.dart **
50
/// {@end-tool}
51 52
class AboutListTile extends StatelessWidget {
  /// Creates a list tile for showing an about box.
Ian Hickson's avatar
Ian Hickson committed
53 54 55 56
  ///
  /// The arguments are all optional. The application name, if omitted, will be
  /// derived from the nearest [Title] widget. The version, icon, and legalese
  /// values default to the empty string.
57
  const AboutListTile({
58
    super.key,
59
    this.icon,
Ian Hickson's avatar
Ian Hickson committed
60 61 62 63 64
    this.child,
    this.applicationName,
    this.applicationVersion,
    this.applicationIcon,
    this.applicationLegalese,
65
    this.aboutBoxChildren,
66
    this.dense,
67
  });
Ian Hickson's avatar
Ian Hickson committed
68 69 70 71 72 73 74

  /// The icon to show for this drawer item.
  ///
  /// By default no icon is shown.
  ///
  /// This is not necessarily the same as the image shown in the dialog box
  /// itself; which is controlled by the [applicationIcon] property.
75
  final Widget? icon;
Ian Hickson's avatar
Ian Hickson committed
76 77 78 79 80

  /// The label to show on this drawer item.
  ///
  /// Defaults to a text widget that says "About Foo" where "Foo" is the
  /// application name specified by [applicationName].
81
  final Widget? child;
Ian Hickson's avatar
Ian Hickson committed
82 83 84 85 86 87 88

  /// The name of the application.
  ///
  /// This string is used in the default label for this drawer item (see
  /// [child]) and as the caption of the [AboutDialog] that is shown.
  ///
  /// Defaults to the value of [Title.title], if a [Title] widget can be found.
89
  /// Otherwise, defaults to [Platform.resolvedExecutable].
90
  final String? applicationName;
Ian Hickson's avatar
Ian Hickson committed
91 92 93 94 95 96

  /// The version of this build of the application.
  ///
  /// This string is shown under the application name in the [AboutDialog].
  ///
  /// Defaults to the empty string.
97
  final String? applicationVersion;
Ian Hickson's avatar
Ian Hickson committed
98 99 100 101 102

  /// The icon to show next to the application name in the [AboutDialog].
  ///
  /// By default no icon is shown.
  ///
103 104 105
  /// Typically this will be an [ImageIcon] widget. It should honor the
  /// [IconTheme]'s [IconThemeData.size].
  ///
Ian Hickson's avatar
Ian Hickson committed
106 107
  /// This is not necessarily the same as the icon shown on the drawer item
  /// itself, which is controlled by the [icon] property.
108
  final Widget? applicationIcon;
Ian Hickson's avatar
Ian Hickson committed
109 110 111 112 113 114

  /// A string to show in small print in the [AboutDialog].
  ///
  /// Typically this is a copyright notice.
  ///
  /// Defaults to the empty string.
115
  final String? applicationLegalese;
Ian Hickson's avatar
Ian Hickson committed
116 117 118 119 120 121 122

  /// Widgets to add to the [AboutDialog] after the name, version, and legalese.
  ///
  /// This could include a link to a Web site, some descriptive text, credits,
  /// or other information to show in the about box.
  ///
  /// Defaults to nothing.
123
  final List<Widget>? aboutBoxChildren;
Ian Hickson's avatar
Ian Hickson committed
124

125 126
  /// Whether this list tile is part of a vertically dense list.
  ///
127
  /// If this property is null, then its value is based on [ListTileThemeData.dense].
128 129
  ///
  /// Dense list tiles default to a smaller height.
130
  final bool? dense;
131

Ian Hickson's avatar
Ian Hickson committed
132 133 134
  @override
  Widget build(BuildContext context) {
    assert(debugCheckHasMaterial(context));
135
    assert(debugCheckHasMaterialLocalizations(context));
136
    return ListTile(
137
      leading: icon,
138
      title: child ?? Text(MaterialLocalizations.of(context).aboutListTileTitle(
139 140 141
        applicationName ?? _defaultApplicationName(context),
      )),
      dense: dense,
142
      onTap: () {
Ian Hickson's avatar
Ian Hickson committed
143 144 145 146 147 148
        showAboutDialog(
          context: context,
          applicationName: applicationName,
          applicationVersion: applicationVersion,
          applicationIcon: applicationIcon,
          applicationLegalese: applicationLegalese,
149
          children: aboutBoxChildren,
Ian Hickson's avatar
Ian Hickson committed
150
        );
151
      },
Ian Hickson's avatar
Ian Hickson committed
152 153 154 155 156 157 158 159 160
    );
  }
}

/// Displays an [AboutDialog], which describes the application and provides a
/// button to show licenses for software used by the application.
///
/// The arguments correspond to the properties on [AboutDialog].
///
161
/// If the application has a [Drawer], consider using [AboutListTile] instead
Ian Hickson's avatar
Ian Hickson committed
162 163 164 165
/// of calling this directly.
///
/// If you do not need an about box in your application, you should at least
/// provide an affordance to call [showLicensePage].
166 167 168
///
/// The licenses shown on the [LicensePage] are those returned by the
/// [LicenseRegistry] API, which can be used to add more licenses to the list.
Ian Hickson's avatar
Ian Hickson committed
169
///
170 171 172
/// The [context], [useRootNavigator], [routeSettings] and [anchorPoint]
/// arguments are passed to [showDialog], the documentation for which discusses
/// how it is used.
Ian Hickson's avatar
Ian Hickson committed
173
void showAboutDialog({
174 175 176 177 178 179
  required BuildContext context,
  String? applicationName,
  String? applicationVersion,
  Widget? applicationIcon,
  String? applicationLegalese,
  List<Widget>? children,
180
  bool useRootNavigator = true,
181
  RouteSettings? routeSettings,
182
  Offset? anchorPoint,
Ian Hickson's avatar
Ian Hickson committed
183
}) {
184
  assert(context != null);
185
  assert(useRootNavigator != null);
186
  showDialog<void>(
Ian Hickson's avatar
Ian Hickson committed
187
    context: context,
188
    useRootNavigator: useRootNavigator,
189
    builder: (BuildContext context) {
190
      return AboutDialog(
191 192 193 194 195 196
        applicationName: applicationName,
        applicationVersion: applicationVersion,
        applicationIcon: applicationIcon,
        applicationLegalese: applicationLegalese,
        children: children,
      );
197
    },
198
    routeSettings: routeSettings,
199
    anchorPoint: anchorPoint,
Ian Hickson's avatar
Ian Hickson committed
200 201 202 203 204 205
  );
}

/// Displays a [LicensePage], which shows licenses for software used by the
/// application.
///
206 207 208 209 210 211 212
/// The application arguments correspond to the properties on [LicensePage].
///
/// The `context` argument is used to look up the [Navigator] for the page.
///
/// The `useRootNavigator` argument is used to determine whether to push the
/// page to the [Navigator] furthest from or nearest to the given `context`. It
/// is `false` by default.
Ian Hickson's avatar
Ian Hickson committed
213
///
214
/// If the application has a [Drawer], consider using [AboutListTile] instead
Ian Hickson's avatar
Ian Hickson committed
215 216 217 218
/// of calling this directly.
///
/// The [AboutDialog] shown by [showAboutDialog] includes a button that calls
/// [showLicensePage].
219 220 221
///
/// The licenses shown on the [LicensePage] are those returned by the
/// [LicenseRegistry] API, which can be used to add more licenses to the list.
Ian Hickson's avatar
Ian Hickson committed
222
void showLicensePage({
223 224 225 226 227
  required BuildContext context,
  String? applicationName,
  String? applicationVersion,
  Widget? applicationIcon,
  String? applicationLegalese,
228
  bool useRootNavigator = false,
Ian Hickson's avatar
Ian Hickson committed
229
}) {
230
  assert(context != null);
231
  assert(useRootNavigator != null);
232
  Navigator.of(context, rootNavigator: useRootNavigator).push(MaterialPageRoute<void>(
233
    builder: (BuildContext context) => LicensePage(
234 235
      applicationName: applicationName,
      applicationVersion: applicationVersion,
236
      applicationIcon: applicationIcon,
237
      applicationLegalese: applicationLegalese,
238
    ),
239
  ));
Ian Hickson's avatar
Ian Hickson committed
240 241
}

242 243 244
/// The amount of vertical space to separate chunks of text.
const double _textVerticalSeparation = 18.0;

Ian Hickson's avatar
Ian Hickson committed
245 246 247 248 249
/// An about box. This is a dialog box with the application's icon, name,
/// version number, and copyright, plus a button to show licenses for software
/// used by the application.
///
/// To show an [AboutDialog], use [showAboutDialog].
250
///
251 252
/// {@youtube 560 315 https://www.youtube.com/watch?v=YFCSODyFxbE}
///
253
/// If the application has a [Drawer], the [AboutListTile] widget can make the
254 255 256 257 258 259 260
/// process of showing an about dialog simpler.
///
/// The [AboutDialog] shown by [showAboutDialog] includes a button that calls
/// [showLicensePage].
///
/// The licenses shown on the [LicensePage] are those returned by the
/// [LicenseRegistry] API, which can be used to add more licenses to the list.
Ian Hickson's avatar
Ian Hickson committed
261 262 263 264 265 266
class AboutDialog extends StatelessWidget {
  /// Creates an about box.
  ///
  /// The arguments are all optional. The application name, if omitted, will be
  /// derived from the nearest [Title] widget. The version, icon, and legalese
  /// values default to the empty string.
267
  const AboutDialog({
268
    super.key,
Ian Hickson's avatar
Ian Hickson committed
269 270 271 272
    this.applicationName,
    this.applicationVersion,
    this.applicationIcon,
    this.applicationLegalese,
273
    this.children,
274
  });
Ian Hickson's avatar
Ian Hickson committed
275 276 277 278

  /// The name of the application.
  ///
  /// Defaults to the value of [Title.title], if a [Title] widget can be found.
279
  /// Otherwise, defaults to [Platform.resolvedExecutable].
280
  final String? applicationName;
Ian Hickson's avatar
Ian Hickson committed
281 282 283 284 285 286

  /// The version of this build of the application.
  ///
  /// This string is shown under the application name.
  ///
  /// Defaults to the empty string.
287
  final String? applicationVersion;
Ian Hickson's avatar
Ian Hickson committed
288 289 290 291

  /// The icon to show next to the application name.
  ///
  /// By default no icon is shown.
292 293 294
  ///
  /// Typically this will be an [ImageIcon] widget. It should honor the
  /// [IconTheme]'s [IconThemeData.size].
295
  final Widget? applicationIcon;
Ian Hickson's avatar
Ian Hickson committed
296 297 298 299 300 301

  /// A string to show in small print.
  ///
  /// Typically this is a copyright notice.
  ///
  /// Defaults to the empty string.
302
  final String? applicationLegalese;
Ian Hickson's avatar
Ian Hickson committed
303 304 305 306 307 308 309

  /// Widgets to add to the dialog box after the name, version, and legalese.
  ///
  /// This could include a link to a Web site, some descriptive text, credits,
  /// or other information to show in the about box.
  ///
  /// Defaults to nothing.
310
  final List<Widget>? children;
Ian Hickson's avatar
Ian Hickson committed
311 312 313

  @override
  Widget build(BuildContext context) {
314
    assert(debugCheckHasMaterialLocalizations(context));
Ian Hickson's avatar
Ian Hickson committed
315 316
    final String name = applicationName ?? _defaultApplicationName(context);
    final String version = applicationVersion ?? _defaultApplicationVersion(context);
317
    final Widget? icon = applicationIcon ?? _defaultApplicationIcon(context);
318
    return AlertDialog(
319 320 321 322 323
      content: ListBody(
        children: <Widget>[
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
324
              if (icon != null) IconTheme(data: Theme.of(context).iconTheme, child: icon),
325 326 327 328 329
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 24.0),
                  child: ListBody(
                    children: <Widget>[
330 331
                      Text(name, style: Theme.of(context).textTheme.headline5),
                      Text(version, style: Theme.of(context).textTheme.bodyText2),
332
                      const SizedBox(height: _textVerticalSeparation),
333
                      Text(applicationLegalese ?? '', style: Theme.of(context).textTheme.caption),
334
                    ],
335 336
                  ),
                ),
337 338 339 340 341
              ),
            ],
          ),
          ...?children,
        ],
342
      ),
Ian Hickson's avatar
Ian Hickson committed
343
      actions: <Widget>[
344
        TextButton(
345
          child: Text(MaterialLocalizations.of(context).viewLicensesButtonLabel),
Ian Hickson's avatar
Ian Hickson committed
346 347 348 349 350 351
          onPressed: () {
            showLicensePage(
              context: context,
              applicationName: applicationName,
              applicationVersion: applicationVersion,
              applicationIcon: applicationIcon,
352
              applicationLegalese: applicationLegalese,
Ian Hickson's avatar
Ian Hickson committed
353
            );
354
          },
Ian Hickson's avatar
Ian Hickson committed
355
        ),
356
        TextButton(
357
          child: Text(MaterialLocalizations.of(context).closeButtonLabel),
Ian Hickson's avatar
Ian Hickson committed
358 359
          onPressed: () {
            Navigator.pop(context);
360
          },
Ian Hickson's avatar
Ian Hickson committed
361
        ),
362
      ],
363
      scrollable: true,
Ian Hickson's avatar
Ian Hickson committed
364 365 366 367 368 369 370
    );
  }
}

/// A page that shows licenses for software used by the application.
///
/// To show a [LicensePage], use [showLicensePage].
371
///
372
/// The [AboutDialog] shown by [showAboutDialog] and [AboutListTile] includes
373 374 375 376
/// a button that calls [showLicensePage].
///
/// The licenses shown on the [LicensePage] are those returned by the
/// [LicenseRegistry] API, which can be used to add more licenses to the list.
377
class LicensePage extends StatefulWidget {
Ian Hickson's avatar
Ian Hickson committed
378 379 380 381 382
  /// Creates a page that shows licenses for software used by the application.
  ///
  /// The arguments are all optional. The application name, if omitted, will be
  /// derived from the nearest [Title] widget. The version and legalese values
  /// default to the empty string.
383 384 385
  ///
  /// The licenses shown on the [LicensePage] are those returned by the
  /// [LicenseRegistry] API, which can be used to add more licenses to the list.
Ian Hickson's avatar
Ian Hickson committed
386
  const LicensePage({
387
    super.key,
Ian Hickson's avatar
Ian Hickson committed
388 389
    this.applicationName,
    this.applicationVersion,
390
    this.applicationIcon,
391
    this.applicationLegalese,
392
  });
Ian Hickson's avatar
Ian Hickson committed
393 394 395 396

  /// The name of the application.
  ///
  /// Defaults to the value of [Title.title], if a [Title] widget can be found.
397
  /// Otherwise, defaults to [Platform.resolvedExecutable].
398
  final String? applicationName;
Ian Hickson's avatar
Ian Hickson committed
399 400 401 402 403 404

  /// The version of this build of the application.
  ///
  /// This string is shown under the application name.
  ///
  /// Defaults to the empty string.
405
  final String? applicationVersion;
Ian Hickson's avatar
Ian Hickson committed
406

407 408 409 410 411 412
  /// The icon to show below the application name.
  ///
  /// By default no icon is shown.
  ///
  /// Typically this will be an [ImageIcon] widget. It should honor the
  /// [IconTheme]'s [IconThemeData.size].
413
  final Widget? applicationIcon;
414

Ian Hickson's avatar
Ian Hickson committed
415 416 417 418 419
  /// A string to show in small print.
  ///
  /// Typically this is a copyright notice.
  ///
  /// Defaults to the empty string.
420
  final String? applicationLegalese;
Ian Hickson's avatar
Ian Hickson committed
421

422
  @override
423
  State<LicensePage> createState() => _LicensePageState();
424 425 426
}

class _LicensePageState extends State<LicensePage> {
427
  final ValueNotifier<int?> selectedId = ValueNotifier<int?>(null);
428

429 430 431 432 433 434
  @override
  void dispose() {
    selectedId.dispose();
    super.dispose();
  }

435 436 437 438
  @override
  Widget build(BuildContext context) {
    return _MasterDetailFlow(
      detailPageFABlessGutterWidth: _getGutterSize(context),
439
      title: Text(MaterialLocalizations.of(context).licensesPageTitle),
440 441 442 443 444
      detailPageBuilder: _packageLicensePage,
      masterViewBuilder: _packagesView,
    );
  }

445
  Widget _packageLicensePage(BuildContext _, Object? args, ScrollController? scrollController) {
446
    assert(args is _DetailArguments);
447
    final _DetailArguments detailArguments = args! as _DetailArguments;
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
    return _PackageLicensePage(
      packageName: detailArguments.packageName,
      licenseEntries: detailArguments.licenseEntries,
      scrollController: scrollController,
    );
  }

  Widget _packagesView(final BuildContext _, final bool isLateral) {
    final Widget about = _AboutProgram(
        name: widget.applicationName ?? _defaultApplicationName(context),
        icon: widget.applicationIcon ?? _defaultApplicationIcon(context),
        version: widget.applicationVersion ?? _defaultApplicationVersion(context),
        legalese: widget.applicationLegalese,
      );
    return _PackagesView(
      about: about,
      isLateral: isLateral,
      selectedId: selectedId,
    );
  }
}

class _AboutProgram extends StatelessWidget {
  const _AboutProgram({
472 473
    required this.name,
    required this.version,
474 475 476
    this.icon,
    this.legalese,
  })  : assert(name != null),
477
        assert(version != null);
478 479 480

  final String name;
  final String version;
481 482
  final Widget? icon;
  final String? legalese;
483 484 485 486 487 488 489 490 491 492 493 494

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(
        horizontal: _getGutterSize(context),
        vertical: 24.0,
      ),
      child: Column(
        children: <Widget>[
          Text(
            name,
495
            style: Theme.of(context).textTheme.headline5,
496 497 498
            textAlign: TextAlign.center,
          ),
          if (icon != null)
499
            IconTheme(data: Theme.of(context).iconTheme, child: icon!),
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
          if (version != '')
            Padding(
              padding: const EdgeInsets.only(bottom: _textVerticalSeparation),
              child: Text(
                version,
                style: Theme.of(context).textTheme.bodyText2,
                textAlign: TextAlign.center,
              ),
            ),
          if (legalese != null && legalese != '')
            Text(
              legalese!,
              style: Theme.of(context).textTheme.caption,
              textAlign: TextAlign.center,
            ),
515 516 517
          const SizedBox(height: _textVerticalSeparation),
          Text(
            'Powered by Flutter',
518
            style: Theme.of(context).textTheme.bodyText2,
519 520 521 522 523 524 525 526 527 528
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }
}

class _PackagesView extends StatefulWidget {
  const _PackagesView({
529 530 531
    required this.about,
    required this.isLateral,
    required this.selectedId,
532
  })  : assert(about != null),
533
        assert(isLateral != null);
534 535 536

  final Widget about;
  final bool isLateral;
537
  final ValueNotifier<int?> selectedId;
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555

  @override
  _PackagesViewState createState() => _PackagesViewState();
}

class _PackagesViewState extends State<_PackagesView> {
  final Future<_LicenseData> licenses = LicenseRegistry.licenses
      .fold<_LicenseData>(
        _LicenseData(),
        (_LicenseData prev, LicenseEntry license) => prev..addLicense(license),
      )
      .then((_LicenseData licenseData) => licenseData..sortPackages());

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<_LicenseData>(
      future: licenses,
      builder: (BuildContext context, AsyncSnapshot<_LicenseData> snapshot) {
556 557 558 559 560
        return LayoutBuilder(
          key: ValueKey<ConnectionState>(snapshot.connectionState),
          builder: (BuildContext context, BoxConstraints constraints) {
            switch (snapshot.connectionState) {
              case ConnectionState.done:
561 562
                _initDefaultDetailPage(snapshot.data!, context);
                return ValueListenableBuilder<int?>(
563
                  valueListenable: widget.selectedId,
564
                  builder: (BuildContext context, int? selectedId, Widget? _) {
565 566
                    return Center(
                      child: Material(
567
                        color: Theme.of(context).cardColor,
568 569 570
                        elevation: 4.0,
                        child: Container(
                          constraints: BoxConstraints.loose(const Size.fromWidth(600.0)),
571
                          child: _packagesList(context, selectedId, snapshot.data!, widget.isLateral),
572
                        ),
573 574 575 576
                      ),
                    );
                  },
                );
577 578 579
              case ConnectionState.none:
              case ConnectionState.active:
              case ConnectionState.waiting:
580
                return Material(
581
                    color: Theme.of(context).cardColor,
582
                    child: Column(
583 584 585 586
                    children: <Widget>[
                      widget.about,
                      const Center(child: CircularProgressIndicator()),
                    ],
587 588 589 590
                  ),
                );
            }
          },
591 592 593 594 595 596
        );
      },
    );
  }

  void _initDefaultDetailPage(_LicenseData data, BuildContext context) {
597 598 599
    if (data.packages.isEmpty) {
      return;
    }
600
    final String packageName = data.packages[widget.selectedId.value ?? 0];
601 602
    final List<int> bindings = data.packageLicenseBindings[packageName]!;
    _MasterDetailFlow.of(context)!.setInitialDetailPage(
603 604 605 606 607 608 609 610 611
      _DetailArguments(
        packageName,
        bindings.map((int i) => data.licenses[i]).toList(growable: false),
      ),
    );
  }

  Widget _packagesList(
    final BuildContext context,
612
    final int? selectedId,
613 614 615
    final _LicenseData data,
    final bool drawSelection,
  ) {
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
    return ListView.builder(
      itemCount: data.packages.length + 1,
      itemBuilder: (BuildContext context, int index) {
        if (index == 0) {
          return widget.about;
        }
        final int packageIndex = index - 1;
        final String packageName = data.packages[packageIndex];
        final List<int> bindings = data.packageLicenseBindings[packageName]!;
        return _PackageListTile(
          packageName: packageName,
          index: packageIndex,
          isSelected: drawSelection && packageIndex == (selectedId ?? 0),
          numberLicenses: bindings.length,
          onTap: () {
            widget.selectedId.value = packageIndex;
            _MasterDetailFlow.of(context)!.openDetailPage(_DetailArguments(
              packageName,
              bindings.map((int i) => data.licenses[i]).toList(growable: false),
            ));
          },
        );
      },
639 640 641 642 643 644
    );
  }
}

class _PackageListTile extends StatelessWidget {
  const _PackageListTile({
645
    required this.packageName,
646
    this.index,
647 648
    required this.isSelected,
    required this.numberLicenses,
649
    this.onTap,
650
});
651 652

  final String packageName;
653
  final int? index;
654 655
  final bool isSelected;
  final int numberLicenses;
656
  final GestureTapCallback? onTap;
657 658 659 660

  @override
  Widget build(BuildContext context) {
    return Ink(
661
      color: isSelected ? Theme.of(context).highlightColor : Theme.of(context).cardColor,
662 663
      child: ListTile(
        title: Text(packageName),
664
        subtitle: Text(MaterialLocalizations.of(context).licensesPackageDetailText(numberLicenses)),
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
        selected: isSelected,
        onTap: onTap,
      ),
    );
  }
}

/// This is a collection of licenses and the packages to which they apply.
/// [packageLicenseBindings] records the m+:n+ relationship between the license
/// and packages as a map of package names to license indexes.
class _LicenseData {
  final List<LicenseEntry> licenses = <LicenseEntry>[];
  final Map<String, List<int>> packageLicenseBindings = <String, List<int>>{};
  final List<String> packages = <String>[];

  // Special treatment for the first package since it should be the package
  // for delivered application.
682
  String? firstPackage;
683 684 685 686 687 688 689 690 691

  void addLicense(LicenseEntry entry) {
    // Before the license can be added, we must first record the packages to
    // which it belongs.
    for (final String package in entry.packages) {
      _addPackage(package);
      // Bind this license to the package using the next index value. This
      // creates a contract that this license must be inserted at this same
      // index value.
692
      packageLicenseBindings[package]!.add(licenses.length);
693 694 695 696
    }
    licenses.add(entry); // Completion of the contract above.
  }

697
  /// Add a package and initialize package license binding. This is a no-op if
698 699 700 701 702 703 704 705 706 707 708 709
  /// the package has been seen before.
  void _addPackage(String package) {
    if (!packageLicenseBindings.containsKey(package)) {
      packageLicenseBindings[package] = <int>[];
      firstPackage ??= package;
      packages.add(package);
    }
  }

  /// Sort the packages using some comparison method, or by the default manner,
  /// which is to put the application package first, followed by every other
  /// package in case-insensitive alphabetical order.
710
  void sortPackages([int Function(String a, String b)? compare]) {
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
    packages.sort(compare ?? (String a, String b) {
      // Based on how LicenseRegistry currently behaves, the first package
      // returned is the end user application license. This should be
      // presented first in the list. So here we make sure that first package
      // remains at the front regardless of alphabetical sorting.
      if (a == firstPackage) {
        return -1;
      }
      if (b == firstPackage) {
        return 1;
      }
      return a.toLowerCase().compareTo(b.toLowerCase());
    });
  }
}

@immutable
class _DetailArguments {
  const _DetailArguments(this.packageName, this.licenseEntries);

  final String packageName;
  final List<LicenseEntry> licenseEntries;

  @override
  bool operator ==(final dynamic other) {
    if (other is _DetailArguments) {
      return other.packageName == packageName;
    }
    return other == this;
  }

  @override
743
  int get hashCode => Object.hash(packageName, Object.hashAll(licenseEntries));
744 745 746 747
}

class _PackageLicensePage extends StatefulWidget {
  const _PackageLicensePage({
748 749 750
    required this.packageName,
    required this.licenseEntries,
    required this.scrollController,
751
  });
752 753 754

  final String packageName;
  final List<LicenseEntry> licenseEntries;
755
  final ScrollController? scrollController;
756 757 758 759 760 761

  @override
  _PackageLicensePageState createState() => _PackageLicensePageState();
}

class _PackageLicensePageState extends State<_PackageLicensePage> {
Ian Hickson's avatar
Ian Hickson committed
762 763 764 765 766 767
  @override
  void initState() {
    super.initState();
    _initLicenses();
  }

768
  final List<Widget> _licenses = <Widget>[];
Ian Hickson's avatar
Ian Hickson committed
769 770
  bool _loaded = false;

771
  Future<void> _initLicenses() async {
772 773 774 775 776 777 778
    int debugFlowId = -1;
    assert(() {
      final Flow flow = Flow.begin();
      Timeline.timeSync('_initLicenses()', () { }, flow: flow);
      debugFlowId = flow.id;
      return true;
    }());
779
    for (final LicenseEntry license in widget.licenseEntries) {
780
      if (!mounted) {
781
        return;
782 783 784 785 786
      }
      assert(() {
        Timeline.timeSync('_initLicenses()', () { }, flow: Flow.step(debugFlowId));
        return true;
      }());
787
      final List<LicenseParagraph> paragraphs =
788
        await SchedulerBinding.instance.scheduleTask<List<LicenseParagraph>>(
789
          license.paragraphs.toList,
790 791 792
          Priority.animation,
          debugLabel: 'License',
        );
793 794 795
      if (!mounted) {
        return;
      }
Ian Hickson's avatar
Ian Hickson committed
796
      setState(() {
797
        _licenses.add(const Padding(
798 799
          padding: EdgeInsets.all(18.0),
          child: Divider(),
Ian Hickson's avatar
Ian Hickson committed
800
        ));
801
        for (final LicenseParagraph paragraph in paragraphs) {
Ian Hickson's avatar
Ian Hickson committed
802
          if (paragraph.indent == LicenseParagraph.centeredIndent) {
803
            _licenses.add(Padding(
804
              padding: const EdgeInsets.only(top: 16.0),
805
              child: Text(
Ian Hickson's avatar
Ian Hickson committed
806
                paragraph.text,
807
                style: const TextStyle(fontWeight: FontWeight.bold),
808 809
                textAlign: TextAlign.center,
              ),
Ian Hickson's avatar
Ian Hickson committed
810 811 812
            ));
          } else {
            assert(paragraph.indent >= 0);
813 814
            _licenses.add(Padding(
              padding: EdgeInsetsDirectional.only(top: 8.0, start: 16.0 * paragraph.indent),
815
              child: Text(paragraph.text),
Ian Hickson's avatar
Ian Hickson committed
816 817
            ));
          }
818
        }
Ian Hickson's avatar
Ian Hickson committed
819
      });
820
    }
Ian Hickson's avatar
Ian Hickson committed
821 822 823
    setState(() {
      _loaded = true;
    });
824 825 826 827
    assert(() {
      Timeline.timeSync('Build scheduled', () { }, flow: Flow.end(debugFlowId));
      return true;
    }());
828 829
  }

Ian Hickson's avatar
Ian Hickson committed
830 831
  @override
  Widget build(BuildContext context) {
832
    assert(debugCheckHasMaterialLocalizations(context));
833
    final MaterialLocalizations localizations = MaterialLocalizations.of(context);
834
    final ThemeData theme = Theme.of(context);
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
    final String title = widget.packageName;
    final String subtitle = localizations.licensesPackageDetailText(widget.licenseEntries.length);
    final double pad = _getGutterSize(context);
    final EdgeInsets padding = EdgeInsets.only(left: pad, right: pad, bottom: pad);
    final List<Widget> listWidgets = <Widget>[
      ..._licenses,
      if (!_loaded)
        const Padding(
          padding: EdgeInsets.symmetric(vertical: 24.0),
          child: Center(
            child: CircularProgressIndicator(),
          ),
        ),
    ];

850
    final Widget page;
851 852 853
    if (widget.scrollController == null) {
      page = Scaffold(
        appBar: AppBar(
854 855 856
          title: _PackageLicensePageTitle(
            title,
            subtitle,
857
            theme.appBarTheme.textTheme ?? theme.primaryTextTheme,
858
          ),
859 860 861 862 863 864 865 866 867 868
        ),
        body: Center(
          child: Material(
            color: theme.cardColor,
            elevation: 4.0,
            child: Container(
              constraints: BoxConstraints.loose(const Size.fromWidth(600.0)),
              child: Localizations.override(
                locale: const Locale('en', 'US'),
                context: context,
869 870 871 872 873 874
                child: ScrollConfiguration(
                  // A Scrollbar is built-in below.
                  behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
                  child: Scrollbar(
                    child: ListView(padding: padding, children: listWidgets),
                  ),
875
                ),
876
              ),
Hans Muller's avatar
Hans Muller committed
877
            ),
878 879
          ),
        ),
880 881 882 883 884 885 886 887
      );
    } else {
      page = CustomScrollView(
        controller: widget.scrollController,
        slivers: <Widget>[
          SliverAppBar(
            automaticallyImplyLeading: false,
            pinned: true,
888
            backgroundColor: theme.cardColor,
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
            title: _PackageLicensePageTitle(title, subtitle, theme.textTheme),
          ),
          SliverPadding(
            padding: padding,
            sliver: SliverList(
              delegate: SliverChildBuilderDelegate(
                (BuildContext context, int index) => Localizations.override(
                  locale: const Locale('en', 'US'),
                  context: context,
                  child: listWidgets[index],
                ),
                childCount: listWidgets.length,
              ),
            ),
          ),
        ],
      );
    }
    return DefaultTextStyle(
908
      style: theme.textTheme.caption!,
909 910 911 912 913 914 915 916 917
      child: page,
    );
  }
}

class _PackageLicensePageTitle extends StatelessWidget {
  const _PackageLicensePageTitle(
    this.title,
    this.subtitle,
918 919
    this.theme,
  );
920 921 922 923 924 925 926

  final String title;
  final String subtitle;
  final TextTheme theme;

  @override
  Widget build(BuildContext context) {
927 928
    final Color? color = Theme.of(context).appBarTheme.foregroundColor;

929 930 931 932
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
933 934
        Text(title, style: theme.headline6?.copyWith(color: color)),
        Text(subtitle, style: theme.subtitle2?.copyWith(color: color)),
935
      ],
Ian Hickson's avatar
Ian Hickson committed
936 937 938 939 940
    );
  }
}

String _defaultApplicationName(BuildContext context) {
941 942 943 944 945 946
  // This doesn't handle the case of the application's title dynamically
  // changing. In theory, we should make Title expose the current application
  // title using an InheritedWidget, and so forth. However, in practice, if
  // someone really wants their application title to change dynamically, they
  // can provide an explicit applicationName to the widgets defined in this
  // file, instead of relying on the default.
947
  final Title? ancestorTitle = context.findAncestorWidgetOfExactType<Title>();
948
  return ancestorTitle?.title ?? Platform.resolvedExecutable.split(Platform.pathSeparator).last;
Ian Hickson's avatar
Ian Hickson committed
949 950 951 952 953 954 955
}

String _defaultApplicationVersion(BuildContext context) {
  // TODO(ianh): Get this from the embedder somehow.
  return '';
}

956
Widget? _defaultApplicationIcon(BuildContext context) {
Ian Hickson's avatar
Ian Hickson committed
957 958 959
  // TODO(ianh): Get this from the embedder somehow.
  return null;
}
960 961 962 963 964 965

const int _materialGutterThreshold = 720;
const double _wideGutterSize = 24.0;
const double _narrowGutterSize = 12.0;

double _getGutterSize(BuildContext context) =>
966
    MediaQuery.of(context).size.width >= _materialGutterThreshold ? _wideGutterSize : _narrowGutterSize;
967 968 969 970 971 972 973 974

/// Signature for the builder callback used by [_MasterDetailFlow].
typedef _MasterViewBuilder = Widget Function(BuildContext context, bool isLateralUI);

/// Signature for the builder callback used by [_MasterDetailFlow.detailPageBuilder].
///
/// scrollController is provided when the page destination is the draggable
/// sheet in the lateral UI. Otherwise, it is null.
975
typedef _DetailPageBuilder = Widget Function(BuildContext context, Object? arguments, ScrollController? scrollController);
976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020

/// Signature for the builder callback used by [_MasterDetailFlow.actionBuilder].
///
/// Builds the actions that go in the app bars constructed for the master and
/// lateral UI pages. actionLevel indicates the intended destination of the
/// return actions.
typedef _ActionBuilder = List<Widget> Function(BuildContext context, _ActionLevel actionLevel);

/// Describes which type of app bar the actions are intended for.
enum _ActionLevel {
  /// Indicates the top app bar in the lateral UI.
  top,

  /// Indicates the master view app bar in the lateral UI.
  view,
}

/// Describes which layout will be used by [_MasterDetailFlow].
enum _LayoutMode {
  /// Use a nested or lateral layout depending on available screen width.
  auto,

  /// Always use a lateral layout.
  lateral,

  /// Always use a nested layout.
  nested,
}

const String _navMaster = 'master';
const String _navDetail = 'detail';
enum _Focus { master, detail }

/// A Master Detail Flow widget. Depending on screen width it builds either a
/// lateral or nested navigation flow between a master view and a detail page.
/// bloc pattern.
///
/// If focus is on detail view, then switching to nested navigation will
/// populate the navigation history with the master page and the detail page on
/// top. Otherwise the focus is on the master view and just the master page
/// is shown.
class _MasterDetailFlow extends StatefulWidget {
  /// Creates a master detail navigation flow which is either nested or
  /// lateral depending on screen width.
  const _MasterDetailFlow({
1021 1022
    required this.detailPageBuilder,
    required this.masterViewBuilder,
1023 1024 1025 1026 1027 1028 1029
    this.automaticallyImplyLeading = true,
    this.detailPageFABlessGutterWidth,
    this.displayMode = _LayoutMode.auto,
    this.title,
  })  : assert(masterViewBuilder != null),
        assert(automaticallyImplyLeading != null),
        assert(detailPageBuilder != null),
1030
        assert(displayMode != null);
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046

  /// Builder for the master view for lateral navigation.
  ///
  /// If [masterPageBuilder] is not supplied the master page required for nested navigation, also
  /// builds the master view inside a [Scaffold] with an [AppBar].
  final _MasterViewBuilder masterViewBuilder;

  /// Builder for the detail page.
  ///
  /// If scrollController == null, the page is intended for nested navigation. The lateral detail
  /// page is inside a [DraggableScrollableSheet] and should have a scrollable element that uses
  /// the [ScrollController] provided. In fact, it is strongly recommended the entire lateral
  /// page is scrollable.
  final _DetailPageBuilder detailPageBuilder;

  /// Override the width of the gutter when there is no floating action button.
1047
  final double? detailPageFABlessGutterWidth;
1048 1049 1050 1051

  /// The title for the lateral UI [AppBar].
  ///
  /// See [AppBar.title].
1052
  final Widget? title;
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072

  /// Override the framework from determining whether to show a leading widget or not.
  ///
  /// See [AppBar.automaticallyImplyLeading].
  final bool automaticallyImplyLeading;

  /// Forces display mode and style.
  final _LayoutMode displayMode;

  @override
  _MasterDetailFlowState createState() => _MasterDetailFlowState();

  /// The master detail flow proxy from the closest instance of this class that encloses the given
  /// context.
  ///
  /// Typical usage is as follows:
  ///
  /// ```dart
  /// _MasterDetailFlow.of(context).openDetailPage(arguments);
  /// ```
1073
  static _MasterDetailFlowProxy? of(BuildContext context) {
1074
    _PageOpener? pageOpener = context.findAncestorStateOfType<_MasterDetailScaffoldState>();
1075 1076
    pageOpener ??= context.findAncestorStateOfType<_MasterDetailFlowState>();
    assert(() {
1077
      if (pageOpener == null) {
1078
        throw FlutterError(
1079 1080
          'Master Detail operation requested with a context that does not include a Master Detail '
          'Flow.\nThe context used to open a detail page from the Master Detail Flow must be '
1081
          'that of a widget that is a descendant of a Master Detail Flow widget.',
1082
        );
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
      }
      return true;
    }());
    return pageOpener != null ? _MasterDetailFlowProxy._(pageOpener) : null;
  }
}

/// Interface for interacting with the [_MasterDetailFlow].
class _MasterDetailFlowProxy implements _PageOpener {
  _MasterDetailFlowProxy._(this._pageOpener);

  final _PageOpener _pageOpener;

  /// Open detail page with arguments.
  @override
  void openDetailPage(Object arguments) =>
      _pageOpener.openDetailPage(arguments);

  /// Set the initial page to be open for the lateral layout. This can be set at any time, but
  /// will have no effect after any calls to openDetailPage.
  @override
  void setInitialDetailPage(Object arguments) =>
      _pageOpener.setInitialDetailPage(arguments);
}

abstract class _PageOpener {
  void openDetailPage(Object arguments);

  void setInitialDetailPage(Object arguments);
}

const int _materialWideDisplayThreshold = 840;

class _MasterDetailFlowState extends State<_MasterDetailFlow> implements _PageOpener {
1117
  /// Tracks whether focus is on the detail or master views. Determines behavior when switching
1118 1119 1120 1121
  /// from lateral to nested navigation.
  _Focus focus = _Focus.master;

  /// Cache of arguments passed when opening a detail page. Used when rebuilding.
1122
  Object? _cachedDetailArguments;
1123 1124

  /// Record of the layout that was built.
1125
  _LayoutMode? _builtLayout;
1126 1127 1128 1129 1130 1131 1132 1133

  /// Key to access navigator in the nested layout.
  final GlobalKey<NavigatorState> _navigatorKey = GlobalKey<NavigatorState>();

  @override
  void openDetailPage(Object arguments) {
    _cachedDetailArguments = arguments;
    if (_builtLayout == _LayoutMode.nested) {
1134
      _navigatorKey.currentState!.pushNamed(_navDetail, arguments: arguments);
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
    } else {
      focus = _Focus.detail;
    }
  }

  @override
  void setInitialDetailPage(Object arguments) {
    _cachedDetailArguments = arguments;
  }

  @override
  Widget build(BuildContext context) {
    switch (widget.displayMode) {
      case _LayoutMode.nested:
        return _nestedUI(context);
      case _LayoutMode.lateral:
        return _lateralUI(context);
      case _LayoutMode.auto:
1153 1154
        return LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) {
          final double availableWidth = constraints.maxWidth;
1155
          if (availableWidth >= _materialWideDisplayThreshold) {
1156 1157 1158 1159 1160
            return _lateralUI(context);
          } else {
            return _nestedUI(context);
          }
        });
1161 1162 1163 1164 1165 1166 1167 1168 1169
    }
  }

  Widget _nestedUI(BuildContext context) {
    _builtLayout = _LayoutMode.nested;
    final MaterialPageRoute<void> masterPageRoute = _masterPageRoute(context);

    return WillPopScope(
      // Push pop check into nested navigator.
1170
      onWillPop: () async => !(await _navigatorKey.currentState!.maybePop()),
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
      child: Navigator(
        key: _navigatorKey,
        initialRoute: 'initial',
        onGenerateInitialRoutes: (NavigatorState navigator, String initialRoute) {
          switch (focus) {
            case _Focus.master:
              return <Route<void>>[masterPageRoute];
            case _Focus.detail:
              return <Route<void>>[
                masterPageRoute,
1181
                _detailPageRoute(_cachedDetailArguments),
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
              ];
          }
        },
        onGenerateRoute: (RouteSettings settings) {
          switch (settings.name) {
            case _navMaster:
              // Matching state to navigation event.
              focus = _Focus.master;
              return masterPageRoute;
            case _navDetail:
              // Matching state to navigation event.
              focus = _Focus.detail;
              // Cache detail page settings.
              _cachedDetailArguments = settings.arguments;
              return _detailPageRoute(_cachedDetailArguments);
            default:
              throw Exception('Unknown route ${settings.name}');
          }
        },
      ),
    );
  }

  MaterialPageRoute<void> _masterPageRoute(BuildContext context) {
    return MaterialPageRoute<dynamic>(
      builder: (BuildContext c) => BlockSemantics(
1208 1209
        child: _MasterPage(
                leading: widget.automaticallyImplyLeading && Navigator.of(context).canPop()
1210
                        ? BackButton(onPressed: () => Navigator.of(context).pop())
1211
                        : null,
1212 1213 1214 1215 1216 1217 1218 1219
                title: widget.title,
                automaticallyImplyLeading: widget.automaticallyImplyLeading,
                masterViewBuilder: widget.masterViewBuilder,
              ),
      ),
    );
  }

1220
  MaterialPageRoute<void> _detailPageRoute(Object? arguments) {
1221 1222 1223 1224 1225
    return MaterialPageRoute<dynamic>(builder: (BuildContext context) {
      return WillPopScope(
        onWillPop: () async {
          // No need for setState() as rebuild happens on navigation pop.
          focus = _Focus.master;
1226
          Navigator.of(context).pop();
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
          return false;
        },
        child: BlockSemantics(child: widget.detailPageBuilder(context, arguments, null)),
      );
    });
  }

  Widget _lateralUI(BuildContext context) {
    _builtLayout = _LayoutMode.lateral;
    return _MasterDetailScaffold(
1237
      actionBuilder: (_, __) => const<Widget>[],
1238
      automaticallyImplyLeading: widget.automaticallyImplyLeading,
1239
      detailPageBuilder: (BuildContext context, Object? args, ScrollController? scrollController) =>
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
          widget.detailPageBuilder(context, args ?? _cachedDetailArguments, scrollController),
      detailPageFABlessGutterWidth: widget.detailPageFABlessGutterWidth,
      initialArguments: _cachedDetailArguments,
      masterViewBuilder: (BuildContext context, bool isLateral) => widget.masterViewBuilder(context, isLateral),
      title: widget.title,
    );
  }
}

class _MasterPage extends StatelessWidget {
  const _MasterPage({
    this.leading,
    this.title,
    this.masterViewBuilder,
1254
    required this.automaticallyImplyLeading,
1255
  });
1256

1257 1258 1259
  final _MasterViewBuilder? masterViewBuilder;
  final Widget? title;
  final Widget? leading;
1260 1261 1262 1263
  final bool automaticallyImplyLeading;

  @override
  Widget build(BuildContext context) {
1264
    return Scaffold(
1265 1266 1267
        appBar: AppBar(
          title: title,
          leading: leading,
1268
          actions: const <Widget>[],
1269 1270
          automaticallyImplyLeading: automaticallyImplyLeading,
        ),
1271
        body: masterViewBuilder!(context, false),
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
      );
  }

}

const double _kCardElevation = 4.0;
const double _kMasterViewWidth = 320.0;
const double _kDetailPageFABlessGutterWidth = 40.0;
const double _kDetailPageFABGutterWidth = 84.0;

class _MasterDetailScaffold extends StatefulWidget {
  const _MasterDetailScaffold({
1284 1285
    required this.detailPageBuilder,
    required this.masterViewBuilder,
1286 1287 1288
    this.actionBuilder,
    this.initialArguments,
    this.title,
1289
    required this.automaticallyImplyLeading,
1290 1291
    this.detailPageFABlessGutterWidth,
  })  : assert(detailPageBuilder != null),
1292
        assert(masterViewBuilder != null);
1293 1294 1295 1296 1297 1298 1299 1300 1301

  final _MasterViewBuilder masterViewBuilder;

  /// Builder for the detail page.
  ///
  /// The detail page is inside a [DraggableScrollableSheet] and should have a scrollable element
  /// that uses the [ScrollController] provided. In fact, it is strongly recommended the entire
  /// lateral page is scrollable.
  final _DetailPageBuilder detailPageBuilder;
1302 1303 1304
  final _ActionBuilder? actionBuilder;
  final Object? initialArguments;
  final Widget? title;
1305
  final bool automaticallyImplyLeading;
1306
  final double? detailPageFABlessGutterWidth;
1307 1308 1309 1310 1311 1312 1313

  @override
  _MasterDetailScaffoldState createState() => _MasterDetailScaffoldState();
}

class _MasterDetailScaffoldState extends State<_MasterDetailScaffold>
    implements _PageOpener {
1314 1315 1316 1317
  late FloatingActionButtonLocation floatingActionButtonLocation;
  late double detailPageFABGutterWidth;
  late double detailPageFABlessGutterWidth;
  late double masterViewWidth;
1318

1319
  final ValueNotifier<Object?> _detailArguments = ValueNotifier<Object?>(null);
1320 1321 1322 1323 1324

  @override
  void initState() {
    super.initState();
    detailPageFABlessGutterWidth = widget.detailPageFABlessGutterWidth ?? _kDetailPageFABlessGutterWidth;
1325 1326 1327
    detailPageFABGutterWidth = _kDetailPageFABGutterWidth;
    masterViewWidth = _kMasterViewWidth;
    floatingActionButtonLocation = FloatingActionButtonLocation.endTop;
1328 1329
  }

1330 1331 1332 1333 1334 1335
  @override
  void dispose() {
    _detailArguments.dispose();
    super.dispose();
  }

1336 1337
  @override
  void openDetailPage(Object arguments) {
1338
    SchedulerBinding.instance.addPostFrameCallback((_) => _detailArguments.value = arguments);
1339
    _MasterDetailFlow.of(context)!.openDetailPage(arguments);
1340 1341 1342 1343
  }

  @override
  void setInitialDetailPage(Object arguments) {
1344
    SchedulerBinding.instance.addPostFrameCallback((_) => _detailArguments.value = arguments);
1345
    _MasterDetailFlow.of(context)!.setInitialDetailPage(arguments);
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Scaffold(
          floatingActionButtonLocation: floatingActionButtonLocation,
          appBar: AppBar(
            title: widget.title,
1356
            actions: widget.actionBuilder!(context, _ActionLevel.top),
1357 1358 1359 1360 1361 1362
            automaticallyImplyLeading: widget.automaticallyImplyLeading,
            bottom: PreferredSize(
              preferredSize: const Size.fromHeight(kToolbarHeight),
              child: Row(
                children: <Widget>[
                  ConstrainedBox(
1363
                    constraints: BoxConstraints.tightFor(width: masterViewWidth),
1364
                    child: IconTheme(
1365
                      data: Theme.of(context).primaryIconTheme,
1366 1367 1368 1369 1370 1371 1372 1373
                      child: Container(
                        alignment: AlignmentDirectional.centerEnd,
                        padding: const EdgeInsets.all(8),
                        child: OverflowBar(
                          spacing: 8,
                          overflowAlignment: OverflowBarAlignment.end,
                          children: widget.actionBuilder!(context, _ActionLevel.view),
                        ),
1374 1375
                      ),
                    ),
1376
                  ),
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387
                ],
              ),
            ),
          ),
          body: _masterPanel(context),
        ),
        // Detail view stacked above main scaffold and master view.
        SafeArea(
          child: Padding(
            padding: EdgeInsetsDirectional.only(
              start: masterViewWidth - _kCardElevation,
1388
              end: detailPageFABlessGutterWidth,
1389
            ),
1390
            child: ValueListenableBuilder<Object?>(
1391
              valueListenable: _detailArguments,
1392
              builder: (BuildContext context, Object? value, Widget? child) {
1393
                return AnimatedSwitcher(
1394 1395 1396 1397 1398 1399 1400 1401
                  transitionBuilder: (Widget child, Animation<double> animation) =>
                    const FadeUpwardsPageTransitionsBuilder().buildTransitions<void>(
                      null,
                      null,
                      animation,
                      null,
                      child,
                    ),
1402 1403
                  duration: const Duration(milliseconds: 500),
                  child: Container(
1404
                    key: ValueKey<Object?>(value ?? widget.initialArguments),
1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
                    constraints: const BoxConstraints.expand(),
                    child: _DetailView(
                      builder: widget.detailPageBuilder,
                      arguments: value ?? widget.initialArguments,
                    ),
                  ),
                );
              },
            ),
          ),
        ),
      ],
    );
  }

  ConstrainedBox _masterPanel(BuildContext context, {bool needsScaffold = false}) {
    return ConstrainedBox(
      constraints: BoxConstraints(maxWidth: masterViewWidth),
      child: needsScaffold
          ? Scaffold(
              appBar: AppBar(
                title: widget.title,
1427
                actions: widget.actionBuilder!(context, _ActionLevel.top),
1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
                automaticallyImplyLeading: widget.automaticallyImplyLeading,
              ),
              body: widget.masterViewBuilder(context, true),
            )
          : widget.masterViewBuilder(context, true),
    );
  }
}

class _DetailView extends StatelessWidget {
  const _DetailView({
1439 1440
    required _DetailPageBuilder builder,
    Object? arguments,
1441 1442
  })  : assert(builder != null),
        _builder = builder,
1443
        _arguments = arguments;
1444 1445

  final _DetailPageBuilder _builder;
1446
  final Object? _arguments;
1447 1448 1449 1450 1451 1452

  @override
  Widget build(BuildContext context) {
    if (_arguments == null) {
      return Container();
    }
1453
    final double screenHeight = MediaQuery.of(context).size.height;
1454 1455
    final double minHeight = (screenHeight - kToolbarHeight) / screenHeight;

1456 1457 1458 1459 1460 1461 1462 1463
    return DraggableScrollableSheet(
      initialChildSize: minHeight,
      minChildSize: minHeight,
      expand: false,
      builder: (BuildContext context, ScrollController controller) {
        return MouseRegion(
          // TODO(TonicArtos): Remove MouseRegion workaround for pointer hover events passing through DraggableScrollableSheet once https://github.com/flutter/flutter/issues/59741 is resolved.
          child: Card(
1464
            color: Theme.of(context).cardColor,
1465 1466
            elevation: _kCardElevation,
            clipBehavior: Clip.antiAlias,
1467
            margin: const EdgeInsets.fromLTRB(_kCardElevation, 0.0, _kCardElevation, 0.0),
1468
            shape: const RoundedRectangleBorder(
1469
              borderRadius: BorderRadius.vertical(top: Radius.circular(3.0)),
1470
            ),
1471 1472 1473 1474 1475 1476 1477 1478
            child: _builder(
              context,
              _arguments,
              controller,
            ),
          ),
        );
      },
1479 1480 1481
    );
  }
}