-
Notifications
You must be signed in to change notification settings - Fork 30.1k
Expand file tree
/
Copy pathtooltip.dart
More file actions
602 lines (553 loc) · 22 KB
/
tooltip.dart
File metadata and controls
602 lines (553 loc) · 22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// @docImport 'package:flutter/widgets.dart';
///
/// @docImport 'app.dart';
/// @docImport 'floating_action_button.dart';
/// @docImport 'icon_button.dart';
/// @docImport 'popup_menu.dart';
library;
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'colors.dart';
import 'text_theme.dart';
import 'theme.dart';
import 'tooltip_theme.dart';
import 'tooltip_visibility.dart';
/// A Material Design tooltip.
///
/// Tooltips provide text labels which help explain the function of a button or
/// other user interface action. Wrap the button in a [Tooltip] widget and provide
/// a message which will be shown when the widget is long pressed.
///
/// Many widgets, such as [IconButton], [FloatingActionButton], and
/// [PopupMenuButton] have a `tooltip` property that, when non-null, causes the
/// widget to include a [Tooltip] in its build.
///
/// Tooltips improve the accessibility of visual widgets by proving a textual
/// representation of the widget, which, for example, can be vocalized by a
/// screen reader.
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=EeEfD5fI-5Q}
///
/// {@tool dartpad}
/// This example show a basic [Tooltip] which has a [Text] as child.
/// [message] contains your label to be shown by the tooltip when
/// the child that Tooltip wraps is hovered over on web or desktop. On mobile,
/// the tooltip is shown when the widget is long pressed.
///
/// This tooltip will default to showing above the [Text] instead of below
/// because its ambient [TooltipThemeData.preferBelow] is false.
/// (See the use of [MaterialApp.theme].)
/// Setting that piece of theme data is recommended to avoid having a finger or
/// cursor hide the tooltip. For other ways to set that piece of theme data see:
///
/// * [Theme.data], [ThemeData.tooltipTheme]
/// * [TooltipTheme.data]
///
/// or it can be set directly on each tooltip with [Tooltip.preferBelow].
///
/// ** See code in examples/api/lib/material/tooltip/tooltip.0.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// This example covers most of the attributes available in Tooltip.
/// `decoration` has been used to give a gradient and borderRadius to Tooltip.
/// `constraints` has been used to set the minimum width of the Tooltip.
/// `preferBelow` is true; the tooltip will prefer showing below [Tooltip]'s child widget.
/// However, it may show the tooltip above if there's not enough space
/// below the widget.
/// `textStyle` has been used to set the font size of the 'message'.
/// `showDuration` accepts a Duration to continue showing the message after the long
/// press has been released or the mouse pointer exits the child widget.
/// `waitDuration` accepts a Duration for which a mouse pointer has to hover over the child
/// widget before the tooltip is shown.
///
/// ** See code in examples/api/lib/material/tooltip/tooltip.1.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// This example shows a rich [Tooltip] that specifies the [richMessage]
/// parameter instead of the [message] parameter (only one of these may be
/// non-null. Any [InlineSpan] can be specified for the [richMessage] attribute,
/// including [WidgetSpan].
///
/// ** See code in examples/api/lib/material/tooltip/tooltip.2.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// This example shows how [Tooltip] can be shown manually with [TooltipTriggerMode.manual]
/// by calling the [TooltipState.ensureTooltipVisible] function.
///
/// ** See code in examples/api/lib/material/tooltip/tooltip.3.dart **
/// {@end-tool}
///
/// See also:
///
/// * <https://material.io/design/components/tooltips.html>
/// * [TooltipTheme] or [ThemeData.tooltipTheme]
/// * [TooltipVisibility]
class Tooltip extends StatefulWidget {
/// Creates a tooltip.
///
/// By default, tooltips should adhere to the
/// [Material specification](https://material.io/design/components/tooltips.html#spec).
/// If the optional constructor parameters are not defined, the values
/// provided by [TooltipTheme.of] will be used if a [TooltipTheme] is present
/// or specified in [ThemeData].
///
/// All parameters that are defined in the constructor will
/// override the default values _and_ the values in [TooltipTheme.of].
///
/// Only one of [message] and [richMessage] may be non-null.
const Tooltip({
super.key,
this.message,
this.richMessage,
@Deprecated(
'Use Tooltip.constraints instead. '
'This feature was deprecated after v3.30.0-0.1.pre.',
)
this.height,
this.constraints,
this.padding,
this.margin,
this.verticalOffset,
this.preferBelow,
this.excludeFromSemantics,
this.decoration,
this.textStyle,
this.textAlign,
this.waitDuration,
this.showDuration,
this.exitDuration,
this.enableTapToDismiss = true,
this.triggerMode,
this.enableFeedback,
this.onTriggered,
this.mouseCursor,
this.ignorePointer,
this.positionDelegate,
this.child,
}) : assert(
(message == null) != (richMessage == null),
'Either `message` or `richMessage` must be specified',
),
assert(
height == null || constraints == null,
'Only one of `height` and `constraints` may be specified.',
);
/// The text to display in the tooltip.
///
/// Only one of [message] and [richMessage] may be non-null.
final String? message;
/// The rich text to display in the tooltip.
///
/// Only one of [message] and [richMessage] may be non-null.
final InlineSpan? richMessage;
/// The minimum height of the [Tooltip]'s message.
@Deprecated(
'Use Tooltip.constraints instead. '
'This feature was deprecated after v3.30.0-0.1.pre.',
)
final double? height;
/// Constrains the size of the [Tooltip]'s message.
///
/// If null, then the [TooltipThemeData.constraints] of the ambient [ThemeData.tooltipTheme]
/// will be used. If that is also null, then a default value will be picked based on the current
/// platform. For desktop platforms, the default value is `BoxConstraints(minHeight: 24.0)`,
/// while for mobile platforms the default value is `BoxConstraints(minHeight: 32.0)`.
final BoxConstraints? constraints;
/// The amount of space by which to inset the [Tooltip]'s message.
///
/// On mobile, defaults to 16.0 logical pixels horizontally and 4.0 vertically.
/// On desktop, defaults to 8.0 logical pixels horizontally and 4.0 vertically.
final EdgeInsetsGeometry? padding;
/// The empty space that surrounds the tooltip.
///
/// Defines the tooltip's outer [Container.margin]. By default, a
/// long tooltip will span the width of its window. If long enough,
/// a tooltip might also span the window's height. This property allows
/// one to define how much space the tooltip must be inset from the edges
/// of their display window.
///
/// If this property is null, then [TooltipThemeData.margin] is used.
/// If [TooltipThemeData.margin] is also null, the default margin is
/// 0.0 logical pixels on all sides.
///
/// See also:
///
/// * [constraints], which allow setting an explicit size for the tooltip.
final EdgeInsetsGeometry? margin;
/// The vertical gap between the widget and the displayed tooltip.
///
/// When [preferBelow] is set to true and tooltips have sufficient space to
/// display themselves, this property defines how much vertical space
/// tooltips will position themselves under their corresponding widgets.
/// Otherwise, tooltips will position themselves above their corresponding
/// widgets with the given offset.
final double? verticalOffset;
/// Whether the tooltip defaults to being displayed below the widget.
///
/// If there is insufficient space to display the tooltip in
/// the preferred direction, the tooltip will be displayed in the opposite
/// direction.
///
/// If this property is null, then [TooltipThemeData.preferBelow] is used.
/// If that is also null, the default value is true.
///
/// Applying [TooltipThemeData.preferBelow]: `false` for the entire app
/// is recommended to avoid having a finger or cursor hide a tooltip.
final bool? preferBelow;
/// Whether the tooltip's [message] or [richMessage] should be excluded from
/// the semantics tree.
///
/// Defaults to false. A tooltip will add a [Semantics] label that is set to
/// [Tooltip.message] if non-null, or the plain text value of
/// [Tooltip.richMessage] otherwise. Set this property to true if the app is
/// going to provide its own custom semantics label.
final bool? excludeFromSemantics;
/// The widget below this widget in the tree.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget? child;
/// Specifies the tooltip's shape and background color.
///
/// The tooltip shape defaults to a rounded rectangle with a border radius of
/// 4.0. Tooltips will also default to an opacity of 90% and with the color
/// [Colors.grey]\[700\] if [ThemeData.brightness] is [Brightness.light], and
/// [Colors.white] if it is [Brightness.dark].
final Decoration? decoration;
/// The style to use for the message of the tooltip.
///
/// If null, the message's [TextStyle] will be determined based on
/// [ThemeData]. If [ThemeData.brightness] is set to [Brightness.dark],
/// [TextTheme.bodyMedium] of [ThemeData.textTheme] will be used with
/// [Colors.white]. Otherwise, if [ThemeData.brightness] is set to
/// [Brightness.light], [TextTheme.bodyMedium] of [ThemeData.textTheme] will be
/// used with [Colors.black].
final TextStyle? textStyle;
/// How the message of the tooltip is aligned horizontally.
///
/// If this property is null, then [TooltipThemeData.textAlign] is used.
/// If [TooltipThemeData.textAlign] is also null, the default value is
/// [TextAlign.start].
final TextAlign? textAlign;
/// {@macro flutter.widgets.RawTooltip.hoverDelay}
final Duration? waitDuration;
/// {@macro flutter.widgets.RawTooltip.touchDelay}
///
/// See also:
///
/// * [exitDuration], which allows configuring the time until a pointer
/// disappears when hovering.
final Duration? showDuration;
/// {@macro flutter.widgets.RawTooltip.dismissDelay}
///
/// See also:
///
/// * [showDuration], which allows configuring the length of time that a
/// tooltip will be visible after touch events are released.
final Duration? exitDuration;
/// {@macro flutter.widgets.RawTooltip.enableTapToDismiss}
final bool enableTapToDismiss;
/// {@macro flutter.widgets.RawTooltip.triggerMode}
///
/// If this property is null, then [TooltipThemeData.triggerMode] is used.
/// If [TooltipThemeData.triggerMode] is also null, the default mode is
/// [TooltipTriggerMode.longPress].
final TooltipTriggerMode? triggerMode;
/// {@macro flutter.widgets.RawTooltip.enableFeedback}
final bool? enableFeedback;
/// {@macro flutter.widgets.RawTooltip.onTriggered}
final TooltipTriggeredCallback? onTriggered;
/// The cursor for a mouse pointer when it enters or is hovering over the
/// widget.
///
/// If this property is null, [MouseCursor.defer] will be used.
final MouseCursor? mouseCursor;
/// Whether this tooltip should be invisible to hit testing.
///
/// If no value is passed, pointer events are ignored unless the tooltip has a
/// [richMessage] instead of a [message].
///
/// See also:
///
/// * [IgnorePointer], for more information about how pointer events are
/// handled or ignored.
final bool? ignorePointer;
/// {@macro flutter.widgets.RawTooltip.positionDelegate}
final TooltipPositionDelegate? positionDelegate;
/// {@macro flutter.widgets.RawTooltip.dismissAllToolTips}
static bool dismissAllToolTips() {
return RawTooltip.dismissAllToolTips();
}
@override
State<Tooltip> createState() => TooltipState();
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(
StringProperty(
'message',
message,
showName: message == null,
defaultValue: message == null ? null : kNoDefaultValue,
),
);
properties.add(
StringProperty(
'richMessage',
richMessage?.toPlainText(),
showName: richMessage == null,
defaultValue: richMessage == null ? null : kNoDefaultValue,
),
);
properties.add(DoubleProperty('height', height, defaultValue: null));
properties.add(
DiagnosticsProperty<BoxConstraints>('constraints', constraints, defaultValue: null),
);
properties.add(DiagnosticsProperty<EdgeInsetsGeometry>('padding', padding, defaultValue: null));
properties.add(DiagnosticsProperty<EdgeInsetsGeometry>('margin', margin, defaultValue: null));
properties.add(DoubleProperty('vertical offset', verticalOffset, defaultValue: null));
properties.add(
FlagProperty(
'position',
value: preferBelow,
ifTrue: 'below',
ifFalse: 'above',
showName: true,
),
);
properties.add(
FlagProperty('semantics', value: excludeFromSemantics, ifTrue: 'excluded', showName: true),
);
properties.add(
DiagnosticsProperty<Duration>('wait duration', waitDuration, defaultValue: null),
);
properties.add(
DiagnosticsProperty<Duration>('show duration', showDuration, defaultValue: null),
);
properties.add(
DiagnosticsProperty<Duration>('exit duration', exitDuration, defaultValue: null),
);
properties.add(
DiagnosticsProperty<TooltipTriggerMode>('triggerMode', triggerMode, defaultValue: null),
);
properties.add(
FlagProperty('enableFeedback', value: enableFeedback, ifTrue: 'true', showName: true),
);
properties.add(DiagnosticsProperty<TextAlign>('textAlign', textAlign, defaultValue: null));
properties.add(
DiagnosticsProperty<TooltipPositionDelegate>(
'positionDelegate',
positionDelegate,
defaultValue: null,
),
);
}
}
/// Contains the state for a [Tooltip].
///
/// This class can be used to programmatically show the Tooltip, see the
/// [ensureTooltipVisible] method.
class TooltipState extends State<Tooltip> with SingleTickerProviderStateMixin {
static const double _defaultVerticalOffset = 24.0;
static const bool _defaultPreferBelow = true;
static const EdgeInsetsGeometry _defaultMargin = EdgeInsets.zero;
static const Duration _defaultShowDuration = Duration(milliseconds: 1500);
static const Duration _defaultExitDuration = Duration(milliseconds: 100);
static const Duration _defaultWaitDuration = Duration.zero;
static const bool _defaultExcludeFromSemantics = false;
static const TooltipTriggerMode _defaultTriggerMode = TooltipTriggerMode.longPress;
static const bool _defaultEnableFeedback = true;
static const TextAlign _defaultTextAlign = TextAlign.start;
final GlobalKey<RawTooltipState> _tooltipKey = GlobalKey<RawTooltipState>();
// From InheritedWidgets
late bool _visible;
late TooltipThemeData _tooltipTheme;
/// The plain text message for this tooltip.
///
/// This value will either come from [widget.message] or [widget.richMessage].
String get _tooltipMessage => widget.message ?? widget.richMessage!.toPlainText();
/// {@macro flutter.widgets.RawTooltipState.ensureTooltipVisible}
bool ensureTooltipVisible() {
return _tooltipKey.currentState?.ensureTooltipVisible() ?? false;
}
@protected
@override
void didChangeDependencies() {
super.didChangeDependencies();
_visible = TooltipVisibility.of(context);
_tooltipTheme = TooltipTheme.of(context);
}
// https://material.io/components/tooltips#specs
double _getDefaultTooltipHeight() {
return switch (Theme.of(context).platform) {
TargetPlatform.macOS || TargetPlatform.linux || TargetPlatform.windows => 24.0,
TargetPlatform.android || TargetPlatform.fuchsia || TargetPlatform.iOS => 32.0,
};
}
EdgeInsets _getDefaultPadding() {
return switch (Theme.of(context).platform) {
TargetPlatform.macOS ||
TargetPlatform.linux ||
TargetPlatform.windows => const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
TargetPlatform.android ||
TargetPlatform.fuchsia ||
TargetPlatform.iOS => const EdgeInsets.symmetric(horizontal: 16.0, vertical: 4.0),
};
}
static double _getDefaultFontSize(TargetPlatform platform) {
return switch (platform) {
TargetPlatform.macOS || TargetPlatform.linux || TargetPlatform.windows => 12.0,
TargetPlatform.android || TargetPlatform.fuchsia || TargetPlatform.iOS => 14.0,
};
}
Offset _getDefaultPositionDelegate(TooltipPositionContext context) {
final double effectiveVerticalOffset =
widget.verticalOffset ?? _tooltipTheme.verticalOffset ?? _defaultVerticalOffset;
final bool effectivePreferBelow =
widget.preferBelow ?? _tooltipTheme.preferBelow ?? _defaultPreferBelow;
final resolvedContext = TooltipPositionContext(
target: context.target,
targetSize: context.targetSize,
tooltipSize: context.tooltipSize,
overlaySize: context.overlaySize,
verticalOffset: effectiveVerticalOffset,
preferBelow: effectivePreferBelow,
);
return widget.positionDelegate?.call(resolvedContext) ??
positionDependentBox(
size: context.overlaySize,
childSize: context.tooltipSize,
target: context.target,
verticalOffset: effectiveVerticalOffset,
preferBelow: effectivePreferBelow,
);
}
@override
Widget build(BuildContext context) {
// If no message is provided, there is no need to create a tooltip overlay
// to show an empty container. In this case, just return the wrapped child
// as is, or SizedBox.shrink if a child is not provided.
if (_tooltipMessage.isEmpty) {
return widget.child ?? const SizedBox.shrink();
}
final (TextStyle defaultTextStyle, BoxDecoration defaultDecoration) = switch (Theme.of(
context,
)) {
ThemeData(
brightness: Brightness.dark,
:final TextTheme textTheme,
:final TargetPlatform platform,
) =>
(
textTheme.bodyMedium!.copyWith(
color: Colors.black,
fontSize: _getDefaultFontSize(platform),
),
BoxDecoration(
color: Colors.white.withOpacity(0.9),
borderRadius: const BorderRadius.all(Radius.circular(4)),
),
),
ThemeData(
brightness: Brightness.light,
:final TextTheme textTheme,
:final TargetPlatform platform,
) =>
(
textTheme.bodyMedium!.copyWith(
color: Colors.white,
fontSize: _getDefaultFontSize(platform),
),
BoxDecoration(
color: Colors.grey[700]!.withOpacity(0.9),
borderRadius: const BorderRadius.all(Radius.circular(4)),
),
),
};
final defaultConstraints = BoxConstraints(
minHeight: widget.height ?? _tooltipTheme.height ?? _getDefaultTooltipHeight(),
);
final Widget tooltipBox = _TooltipBox(
constraints: widget.constraints ?? _tooltipTheme.constraints ?? defaultConstraints,
textStyle: widget.textStyle ?? _tooltipTheme.textStyle ?? defaultTextStyle,
textAlign: widget.textAlign ?? _tooltipTheme.textAlign ?? _defaultTextAlign,
decoration: widget.decoration ?? _tooltipTheme.decoration ?? defaultDecoration,
padding: widget.padding ?? _tooltipTheme.padding ?? _getDefaultPadding(),
margin: widget.margin ?? _tooltipTheme.margin ?? _defaultMargin,
richMessage: widget.richMessage ?? TextSpan(text: widget.message),
);
Widget effectiveChild = MouseRegion(
cursor: widget.mouseCursor ?? MouseCursor.defer,
child: widget.child ?? const SizedBox.shrink(),
);
final bool excludeFromSemantics =
widget.excludeFromSemantics ??
_tooltipTheme.excludeFromSemantics ??
_defaultExcludeFromSemantics;
if (_visible) {
effectiveChild = RawTooltip(
key: _tooltipKey,
semanticsTooltip: excludeFromSemantics ? null : _tooltipMessage,
tooltipBuilder: (BuildContext context, Animation<double> animation) =>
FadeTransition(opacity: animation, child: tooltipBox),
touchDelay: widget.showDuration ?? _tooltipTheme.showDuration ?? _defaultShowDuration,
triggerMode: widget.triggerMode ?? _tooltipTheme.triggerMode ?? _defaultTriggerMode,
enableFeedback:
widget.enableFeedback ?? _tooltipTheme.enableFeedback ?? _defaultEnableFeedback,
hoverDelay: widget.waitDuration ?? _tooltipTheme.waitDuration ?? _defaultWaitDuration,
enableTapToDismiss: widget.enableTapToDismiss,
onTriggered: widget.onTriggered,
dismissDelay: widget.exitDuration ?? _tooltipTheme.exitDuration ?? _defaultExitDuration,
positionDelegate: _getDefaultPositionDelegate,
ignorePointer: widget.ignorePointer ?? widget.message != null,
child: effectiveChild,
);
}
return effectiveChild;
}
}
class _TooltipBox extends StatelessWidget {
const _TooltipBox({
required this.constraints,
required this.textStyle,
required this.textAlign,
required this.decoration,
required this.padding,
required this.margin,
required this.richMessage,
});
final BoxConstraints constraints;
final TextStyle textStyle;
final TextAlign textAlign;
final Decoration? decoration;
final EdgeInsetsGeometry? padding;
final EdgeInsetsGeometry? margin;
final InlineSpan richMessage;
@override
Widget build(BuildContext context) {
return ConstrainedBox(
constraints: constraints,
child: DefaultTextStyle(
style: textStyle,
textAlign: textAlign,
child: Container(
decoration: decoration,
padding: padding,
margin: margin,
child: Center(
widthFactor: 1.0,
heightFactor: 1.0,
child: Text.rich(richMessage, style: textStyle, textAlign: textAlign),
),
),
),
);
}
}