user_accounts_drawer_header.dart 12.7 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6
import 'dart:math' as math;

7
import 'package:flutter/widgets.dart';
8

9
import 'colors.dart';
10
import 'debug.dart';
11 12 13
import 'drawer_header.dart';
import 'icons.dart';
import 'ink_well.dart';
14
import 'material_localizations.dart';
15
import 'theme.dart';
16

17
class _AccountPictures extends StatelessWidget {
18
  const _AccountPictures({
19 20
    this.currentAccountPicture,
    this.otherAccountsPictures,
21 22
    this.currentAccountPictureSize,
    this.otherAccountsPicturesSize,
23
  });
24

25 26
  final Widget? currentAccountPicture;
  final List<Widget>? otherAccountsPictures;
27 28
  final Size? currentAccountPictureSize;
  final Size? otherAccountsPicturesSize;
29 30 31

  @override
  Widget build(BuildContext context) {
32
    return Stack(
33
      children: <Widget>[
34
        PositionedDirectional(
35
          top: 0.0,
36
          end: 0.0,
37
          child: Row(
38
            children: (otherAccountsPictures ?? <Widget>[]).take(3).map<Widget>((Widget picture) {
39
              return Padding(
40
                padding: const EdgeInsetsDirectional.only(start: 8.0),
41
                child: Semantics(
42
                  container: true,
43 44 45 46 47 48 49
                  child: Padding(
                    padding: const EdgeInsets.only(left: 8.0, bottom: 8.0),
                    child: SizedBox.fromSize(
                      size: otherAccountsPicturesSize,
                      child: picture,
                    ),
                  ),
50
                ),
51 52 53 54
              );
            }).toList(),
          ),
        ),
55
        Positioned(
56
          top: 0.0,
57
          child: Semantics(
58
            explicitChildNodes: true,
59 60
            child: SizedBox.fromSize(
              size: currentAccountPictureSize,
61
              child: currentAccountPicture,
62
            ),
63 64 65 66 67 68 69
          ),
        ),
      ],
    );
  }
}

70
class _AccountDetails extends StatefulWidget {
71
  const _AccountDetails({
72 73
    required this.accountName,
    required this.accountEmail,
74
    this.onTap,
75
    required this.isOpen,
76
    this.arrowColor,
77
  });
78

79 80 81
  final Widget? accountName;
  final Widget? accountEmail;
  final VoidCallback? onTap;
82
  final bool isOpen;
83
  final Color? arrowColor;
84

85 86 87 88 89
  @override
  _AccountDetailsState createState() => _AccountDetailsState();
}

class _AccountDetailsState extends State<_AccountDetails> with SingleTickerProviderStateMixin {
90 91
  late Animation<double> _animation;
  late AnimationController _controller;
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
  @override
  void initState () {
    super.initState();
    _controller = AnimationController(
      value: widget.isOpen ? 1.0 : 0.0,
      duration: const Duration(milliseconds: 200),
      vsync: this,
    );
    _animation = CurvedAnimation(
      parent: _controller,
      curve: Curves.fastOutSlowIn,
      reverseCurve: Curves.fastOutSlowIn.flipped,
    )
      ..addListener(() => setState(() {
        // [animation]'s value has changed here.
      }));
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  void didUpdateWidget (_AccountDetails oldWidget) {
    super.didUpdateWidget(oldWidget);
119 120 121 122 123 124
    // If the state of the arrow did not change, there is no need to trigger the animation
    if (oldWidget.isOpen == widget.isOpen) {
      return;
    }

    if (widget.isOpen) {
125 126 127 128 129 130
      _controller.forward();
    } else {
      _controller.reverse();
    }
  }

131 132
  @override
  Widget build(BuildContext context) {
133
    assert(debugCheckHasDirectionality(context));
134
    assert(debugCheckHasMaterialLocalizations(context));
135
    assert(debugCheckHasMaterialLocalizations(context));
136

137
    final ThemeData theme = Theme.of(context);
138
    final MaterialLocalizations localizations = MaterialLocalizations.of(context);
139

140 141
    Widget accountDetails = CustomMultiChildLayout(
      delegate: _AccountDetailsLayout(
142
        textDirection: Directionality.of(context),
143 144 145 146 147 148 149 150
      ),
      children: <Widget>[
        if (widget.accountName != null)
          LayoutId(
            id: _AccountDetailsLayout.accountName,
            child: Padding(
              padding: const EdgeInsets.symmetric(vertical: 2.0),
              child: DefaultTextStyle(
151
                style: theme.primaryTextTheme.bodyLarge!,
152
                overflow: TextOverflow.ellipsis,
153
                child: widget.accountName!,
154 155
              ),
            ),
156
          ),
157 158 159 160 161 162
        if (widget.accountEmail != null)
          LayoutId(
            id: _AccountDetailsLayout.accountEmail,
            child: Padding(
              padding: const EdgeInsets.symmetric(vertical: 2.0),
              child: DefaultTextStyle(
163
                style: theme.primaryTextTheme.bodyMedium!,
164
                overflow: TextOverflow.ellipsis,
165
                child: widget.accountEmail!,
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
              ),
            ),
          ),
        if (widget.onTap != null)
          LayoutId(
            id: _AccountDetailsLayout.dropdownIcon,
            child: Semantics(
              container: true,
              button: true,
              onTap: widget.onTap,
              child: SizedBox(
                height: _kAccountDetailsHeight,
                width: _kAccountDetailsHeight,
                child: Center(
                  child: Transform.rotate(
                    angle: _animation.value * math.pi,
                    child: Icon(
                      Icons.arrow_drop_down,
                      color: widget.arrowColor,
                      semanticLabel: widget.isOpen
186 187
                          ? localizations.hideAccountsLabel
                          : localizations.showAccountsLabel,
188 189
                    ),
                  ),
190
                ),
191 192 193
              ),
            ),
          ),
194
      ],
195 196
    );

197
    if (widget.onTap != null) {
198
      accountDetails = InkWell(
199
        onTap: widget.onTap,
200
        excludeFromSemantics: true,
201
        child: accountDetails,
202 203
      );
    }
204

205
    return SizedBox(
206
      height: _kAccountDetailsHeight,
207
      child: accountDetails,
208 209 210 211
    );
  }
}

212 213 214 215
const double _kAccountDetailsHeight = 56.0;

class _AccountDetailsLayout extends MultiChildLayoutDelegate {

216
  _AccountDetailsLayout({ required this.textDirection });
217

218 219 220
  static const String accountName = 'accountName';
  static const String accountEmail = 'accountEmail';
  static const String dropdownIcon = 'dropdownIcon';
221 222 223 224 225

  final TextDirection textDirection;

  @override
  void performLayout(Size size) {
226
    Size? iconSize;
227 228
    if (hasChild(dropdownIcon)) {
      // place the dropdown icon in bottom right (LTR) or bottom left (RTL)
229
      iconSize = layoutChild(dropdownIcon, BoxConstraints.loose(size));
230 231 232
      positionChild(dropdownIcon, _offsetForIcon(size, iconSize));
    }

233
    final String? bottomLine = hasChild(accountEmail) ? accountEmail : (hasChild(accountName) ? accountName : null);
234 235

    if (bottomLine != null) {
236
      final Size constraintSize = iconSize == null ? size : Size(size.width - iconSize.width, size.height);
237 238 239
      iconSize ??= const Size(_kAccountDetailsHeight, _kAccountDetailsHeight);

      // place bottom line center at same height as icon center
240
      final Size bottomLineSize = layoutChild(bottomLine, BoxConstraints.loose(constraintSize));
241 242 243 244 245
      final Offset bottomLineOffset = _offsetForBottomLine(size, iconSize, bottomLineSize);
      positionChild(bottomLine, bottomLineOffset);

      // place account name above account email
      if (bottomLine == accountEmail && hasChild(accountName)) {
246
        final Size nameSize = layoutChild(accountName, BoxConstraints.loose(constraintSize));
247 248 249 250 251 252 253 254 255 256 257
        positionChild(accountName, _offsetForName(size, nameSize, bottomLineOffset));
      }
    }
  }

  @override
  bool shouldRelayout(MultiChildLayoutDelegate oldDelegate) => true;

  Offset _offsetForIcon(Size size, Size iconSize) {
    switch (textDirection) {
      case TextDirection.ltr:
258
        return Offset(size.width - iconSize.width, size.height - iconSize.height);
259
      case TextDirection.rtl:
260
        return Offset(0.0, size.height - iconSize.height);
261 262 263 264 265 266 267
    }
  }

  Offset _offsetForBottomLine(Size size, Size iconSize, Size bottomLineSize) {
    final double y = size.height - 0.5 * iconSize.height - 0.5 * bottomLineSize.height;
    switch (textDirection) {
      case TextDirection.ltr:
268
        return Offset(0.0, y);
269
      case TextDirection.rtl:
270
        return Offset(size.width - bottomLineSize.width, y);
271 272 273 274 275 276 277
    }
  }

  Offset _offsetForName(Size size, Size nameSize, Offset bottomLineOffset) {
    final double y = bottomLineOffset.dy - nameSize.height;
    switch (textDirection) {
      case TextDirection.ltr:
278
        return Offset(0.0, y);
279
      case TextDirection.rtl:
280
        return Offset(size.width - nameSize.width, y);
281 282 283 284
    }
  }
}

285
/// A Material Design [Drawer] header that identifies the app's user.
286 287 288 289 290
///
/// Requires one of its ancestors to be a [Material] widget.
///
/// See also:
///
291
///  * [DrawerHeader], for a drawer header that doesn't show user accounts.
292
///  * <https://material.io/design/components/navigation-drawer.html#anatomy>
293
class UserAccountsDrawerHeader extends StatefulWidget {
294
  /// Creates a Material Design drawer header.
295 296
  ///
  /// Requires one of its ancestors to be a [Material] widget.
297
  const UserAccountsDrawerHeader({
298
    super.key,
299
    this.decoration,
300
    this.margin = const EdgeInsets.only(bottom: 8.0),
301 302
    this.currentAccountPicture,
    this.otherAccountsPictures,
303 304
    this.currentAccountPictureSize = const Size.square(72.0),
    this.otherAccountsPicturesSize = const Size.square(40.0),
305 306
    required this.accountName,
    required this.accountEmail,
307
    this.onDetailsPressed,
308
    this.arrowColor = Colors.white,
309
  });
310

311 312
  /// The header's background. If decoration is null then a [BoxDecoration]
  /// with its background color set to the current theme's primaryColor is used.
313
  final Decoration? decoration;
314

315
  /// The margin around the drawer header.
316
  final EdgeInsetsGeometry? margin;
317

318 319
  /// A widget placed in the upper-left corner that represents the current
  /// user's account. Normally a [CircleAvatar].
320
  final Widget? currentAccountPicture;
321

322 323 324
  /// A list of widgets that represent the current user's other accounts.
  /// Up to three of these widgets will be arranged in a row in the header's
  /// upper-right corner. Normally a list of [CircleAvatar] widgets.
325
  final List<Widget>? otherAccountsPictures;
326

327 328 329 330 331 332
  /// The size of the [currentAccountPicture].
  final Size currentAccountPictureSize;

  /// The size of each widget in [otherAccountsPicturesSize].
  final Size otherAccountsPicturesSize;

333 334
  /// A widget that represents the user's current account name. It is
  /// displayed on the left, below the [currentAccountPicture].
335
  final Widget? accountName;
336

337 338
  /// A widget that represents the email address of the user's current account.
  /// It is displayed on the left, below the [accountName].
339
  final Widget? accountEmail;
340

341 342
  /// A callback that is called when the horizontal area which contains the
  /// [accountName] and [accountEmail] is tapped.
343
  final VoidCallback? onDetailsPressed;
344

345 346 347
  /// The [Color] of the arrow icon.
  final Color arrowColor;

348
  @override
349
  State<UserAccountsDrawerHeader> createState() => _UserAccountsDrawerHeaderState();
350 351 352
}

class _UserAccountsDrawerHeaderState extends State<UserAccountsDrawerHeader> {
353
  bool _isOpen = false;
354

355 356 357 358
  void _handleDetailsPressed() {
    setState(() {
      _isOpen = !_isOpen;
    });
359
    widget.onDetailsPressed!();
360 361
  }

362 363 364
  @override
  Widget build(BuildContext context) {
    assert(debugCheckHasMaterial(context));
365
    assert(debugCheckHasMaterialLocalizations(context));
366
    return Semantics(
367
      container: true,
368
      label: MaterialLocalizations.of(context).signedInLabel,
369
      child: DrawerHeader(
370
        decoration: widget.decoration ?? BoxDecoration(color: Theme.of(context).colorScheme.primary),
371 372
        margin: widget.margin,
        padding: const EdgeInsetsDirectional.only(top: 16.0, start: 16.0),
373
        child: SafeArea(
374
          bottom: false,
375
          child: Column(
376 377
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
378 379
              Expanded(
                child: Padding(
380
                  padding: const EdgeInsetsDirectional.only(end: 16.0),
381
                  child: _AccountPictures(
382 383
                    currentAccountPicture: widget.currentAccountPicture,
                    otherAccountsPictures: widget.otherAccountsPictures,
384 385
                    currentAccountPictureSize: widget.currentAccountPictureSize,
                    otherAccountsPicturesSize: widget.otherAccountsPicturesSize,
386
                  ),
387
                ),
388
              ),
389
              _AccountDetails(
390 391 392 393
                accountName: widget.accountName,
                accountEmail: widget.accountEmail,
                isOpen: _isOpen,
                onTap: widget.onDetailsPressed == null ? null : _handleDetailsPressed,
394
                arrowColor: widget.arrowColor,
395 396 397
              ),
            ],
          ),
398
        ),
399
      ),
400 401 402
    );
  }
}