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

5
import 'package:flutter/foundation.dart';
6
import 'package:flutter/gestures.dart';
7
import 'package:flutter/rendering.dart';
8
import 'package:flutter/services.dart';
9

Adam Barth's avatar
Adam Barth committed
10
import 'basic.dart';
11
import 'debug.dart';
Adam Barth's avatar
Adam Barth committed
12
import 'framework.dart';
Hixie's avatar
Hixie committed
13
import 'gesture_detector.dart';
Adam Barth's avatar
Adam Barth committed
14
import 'navigator.dart';
15 16
import 'transitions.dart';

17
/// A widget that prevents the user from interacting with widgets behind itself.
18 19 20 21 22 23 24 25 26 27 28 29 30
///
/// The modal barrier is the scrim that is rendered behind each route, which
/// generally prevents the user from interacting with the route below the
/// current route, and normally partially obscures such routes.
///
/// For example, when a dialog is on the screen, the page below the dialog is
/// usually darkened by the modal barrier.
///
/// See also:
///
///  * [ModalRoute], which indirectly uses this widget.
///  * [AnimatedModalBarrier], which is similar but takes an animated [color]
///    instead of a single color value.
31
class ModalBarrier extends StatelessWidget {
32
  /// Creates a widget that blocks user interaction.
33
  const ModalBarrier({
34
    Key? key,
Hixie's avatar
Hixie committed
35
    this.color,
36
    this.dismissible = true,
37
    this.semanticsLabel,
38
    this.barrierSemanticsDismissible = true,
39 40
  }) : super(key: key);

41
  /// If non-null, fill the barrier with this color.
42 43 44 45 46
  ///
  /// See also:
  ///
  ///  * [ModalRoute.barrierColor], which controls this property for the
  ///    [ModalBarrier] built by [ModalRoute] pages.
47
  final Color? color;
48 49

  /// Whether touching the barrier will pop the current route off the [Navigator].
50 51 52 53 54
  ///
  /// See also:
  ///
  ///  * [ModalRoute.barrierDismissible], which controls this property for the
  ///    [ModalBarrier] built by [ModalRoute] pages.
55
  final bool dismissible;
Adam Barth's avatar
Adam Barth committed
56

57 58 59
  /// Whether the modal barrier semantics are included in the semantics tree.
  ///
  /// See also:
60
  ///
61 62
  ///  * [ModalRoute.semanticsDismissible], which controls this property for
  ///    the [ModalBarrier] built by [ModalRoute] pages.
63
  final bool? barrierSemanticsDismissible;
64

65
  /// Semantics label used for the barrier if it is [dismissible].
66 67 68 69 70 71 72 73
  ///
  /// The semantics label is read out by accessibility tools (e.g. TalkBack
  /// on Android and VoiceOver on iOS) when the barrier is focused.
  ///
  /// See also:
  ///
  ///  * [ModalRoute.barrierLabel], which controls this property for the
  ///    [ModalBarrier] built by [ModalRoute] pages.
74
  final String? semanticsLabel;
75

76
  @override
Adam Barth's avatar
Adam Barth committed
77
  Widget build(BuildContext context) {
78
    assert(!dismissible || semanticsLabel == null || debugCheckHasDirectionality(context));
79
    final bool platformSupportsDismissingBarrier;
80 81 82
    switch (defaultTargetPlatform) {
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
83 84
      case TargetPlatform.linux:
      case TargetPlatform.windows:
85 86 87
        platformSupportsDismissingBarrier = false;
        break;
      case TargetPlatform.iOS:
88
      case TargetPlatform.macOS:
89 90 91 92 93
        platformSupportsDismissingBarrier = true;
        break;
    }
    assert(platformSupportsDismissingBarrier != null);
    final bool semanticsDismissible = dismissible && platformSupportsDismissingBarrier;
94
    final bool modalBarrierSemanticsDismissible = barrierSemanticsDismissible ?? semanticsDismissible;
95 96 97 98 99

    void handleDismiss() {
      Navigator.maybePop(context);
    }

100 101
    return BlockSemantics(
      child: ExcludeSemantics(
102 103 104
        // On Android, the back button is used to dismiss a modal. On iOS, some
        // modal barriers are not dismissible in accessibility mode.
        excluding: !semanticsDismissible || !modalBarrierSemanticsDismissible,
105
        child: _ModalBarrierGestureDetector(
106
          onDismiss: () {
107
            if (dismissible)
108
              handleDismiss();
109 110
            else
              SystemSound.play(SystemSoundType.alert);
111
          },
112
          child: Semantics(
113
            label: semanticsDismissible ? semanticsLabel : null,
114
            onDismiss: semanticsDismissible ? handleDismiss : null,
115
            textDirection: semanticsDismissible && semanticsLabel != null ? Directionality.of(context) : null,
116
            child: MouseRegion(
117
              cursor: SystemMouseCursors.basic,
118 119 120
              opaque: true,
              child: ConstrainedBox(
                constraints: const BoxConstraints.expand(),
121 122
                child: color == null ? null : ColoredBox(
                  color: color!,
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
/// A widget that prevents the user from interacting with widgets behind itself,
/// and can be configured with an animated color value.
///
/// The modal barrier is the scrim that is rendered behind each route, which
/// generally prevents the user from interacting with the route below the
/// current route, and normally partially obscures such routes.
///
/// For example, when a dialog is on the screen, the page below the dialog is
/// usually darkened by the modal barrier.
///
/// This widget is similar to [ModalBarrier] except that it takes an animated
/// [color] instead of a single color.
///
/// See also:
///
///  * [ModalRoute], which uses this widget.
149
class AnimatedModalBarrier extends AnimatedWidget {
150
  /// Creates a widget that blocks user interaction.
151
  const AnimatedModalBarrier({
152 153
    Key? key,
    required Animation<Color?> color,
154
    this.dismissible = true,
155
    this.semanticsLabel,
156
    this.barrierSemanticsDismissible,
157
  }) : super(key: key, listenable: color);
158

159
  /// If non-null, fill the barrier with this color.
160 161 162 163 164
  ///
  /// See also:
  ///
  ///  * [ModalRoute.barrierColor], which controls this property for the
  ///    [AnimatedModalBarrier] built by [ModalRoute] pages.
165
  Animation<Color?> get color => listenable as Animation<Color?>;
166 167

  /// Whether touching the barrier will pop the current route off the [Navigator].
168 169 170 171 172
  ///
  /// See also:
  ///
  ///  * [ModalRoute.barrierDismissible], which controls this property for the
  ///    [AnimatedModalBarrier] built by [ModalRoute] pages.
173
  final bool dismissible;
174

175
  /// Semantics label used for the barrier if it is [dismissible].
176 177 178 179 180 181 182
  ///
  /// The semantics label is read out by accessibility tools (e.g. TalkBack
  /// on Android and VoiceOver on iOS) when the barrier is focused.
  /// See also:
  ///
  ///  * [ModalRoute.barrierLabel], which controls this property for the
  ///    [ModalBarrier] built by [ModalRoute] pages.
183
  final String? semanticsLabel;
184

185 186 187
  /// Whether the modal barrier semantics are included in the semantics tree.
  ///
  /// See also:
188
  ///
189 190
  ///  * [ModalRoute.semanticsDismissible], which controls this property for
  ///    the [ModalBarrier] built by [ModalRoute] pages.
191
  final bool? barrierSemanticsDismissible;
192

193
  @override
194
  Widget build(BuildContext context) {
195
    return ModalBarrier(
196
      color: color.value,
197
      dismissible: dismissible,
198
      semanticsLabel: semanticsLabel,
199
      barrierSemanticsDismissible: barrierSemanticsDismissible,
200 201 202
    );
  }
}
203 204 205 206 207

// Recognizes tap down by any pointer button.
//
// It is similar to [TapGestureRecognizer.onTapDown], but accepts any single
// button, which means the gesture also takes parts in gesture arenas.
208
class _AnyTapGestureRecognizer extends BaseTapGestureRecognizer {
209
  _AnyTapGestureRecognizer({ Object? debugOwner })
210
    : super(debugOwner: debugOwner);
211

212
  VoidCallback? onAnyTapUp;
213

214
  @protected
215
  @override
216
  bool isPointerAllowed(PointerDownEvent event) {
217
    if (onAnyTapUp == null)
218 219
      return false;
    return super.isPointerAllowed(event);
220 221
  }

222
  @protected
223
  @override
224
  void handleTapDown({PointerDownEvent? down}) {
225
    // Do nothing.
226 227
  }

228
  @protected
229
  @override
230
  void handleTapUp({PointerDownEvent? down, PointerUpEvent? up}) {
231
    onAnyTapUp?.call();
232 233
  }

234
  @protected
235
  @override
236
  void handleTapCancel({PointerDownEvent? down, PointerCancelEvent? cancel, String? reason}) {
237
    // Do nothing.
238 239 240 241 242 243 244
  }

  @override
  String get debugDescription => 'any tap';
}

class _ModalBarrierSemanticsDelegate extends SemanticsGestureDelegate {
245
  const _ModalBarrierSemanticsDelegate({this.onDismiss});
246

247
  final VoidCallback? onDismiss;
248 249 250

  @override
  void assignSemantics(RenderSemanticsGestureHandler renderObject) {
251
    renderObject.onTap = onDismiss;
252 253 254 255 256
  }
}


class _AnyTapGestureRecognizerFactory extends GestureRecognizerFactory<_AnyTapGestureRecognizer> {
257
  const _AnyTapGestureRecognizerFactory({this.onAnyTapUp});
258

259
  final VoidCallback? onAnyTapUp;
260 261 262 263 264 265

  @override
  _AnyTapGestureRecognizer constructor() => _AnyTapGestureRecognizer();

  @override
  void initializer(_AnyTapGestureRecognizer instance) {
266
    instance.onAnyTapUp = onAnyTapUp;
267 268 269 270 271 272 273
  }
}

// A GestureDetector used by ModalBarrier. It only has one callback,
// [onAnyTapDown], which recognizes tap down unconditionally.
class _ModalBarrierGestureDetector extends StatelessWidget {
  const _ModalBarrierGestureDetector({
274 275 276
    Key? key,
    required this.child,
    required this.onDismiss,
277
  }) : assert(child != null),
278
       assert(onDismiss != null),
279 280 281 282 283 284
       super(key: key);

  /// The widget below this widget in the tree.
  /// See [RawGestureDetector.child].
  final Widget child;

285 286 287
  /// Immediately called when an event that should dismiss the modal barrier
  /// has happened.
  final VoidCallback onDismiss;
288 289 290 291

  @override
  Widget build(BuildContext context) {
    final Map<Type, GestureRecognizerFactory> gestures = <Type, GestureRecognizerFactory>{
292
      _AnyTapGestureRecognizer: _AnyTapGestureRecognizerFactory(onAnyTapUp: onDismiss),
293 294 295 296 297
    };

    return RawGestureDetector(
      gestures: gestures,
      behavior: HitTestBehavior.opaque,
298
      semantics: _ModalBarrierSemanticsDelegate(onDismiss: onDismiss),
299 300 301 302
      child: child,
    );
  }
}