will_pop_scope.dart 2.33 KB
Newer Older
1 2 3 4 5 6 7
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:flutter/foundation.dart';

import 'framework.dart';
8
import 'navigator.dart';
9 10 11 12 13 14 15
import 'routes.dart';

/// Registers a callback to veto attempts by the user to dismiss the enclosing
/// [ModalRoute].
///
/// See also:
///
16
///  * [ModalRoute.addScopedWillPopCallback] and [ModalRoute.removeScopedWillPopCallback],
17 18 19 20 21 22
///    which this widget uses to register and unregister [onWillPop].
class WillPopScope extends StatefulWidget {
  /// Creates a widget that registers a callback to veto attempts by the user to
  /// dismiss the enclosing [ModalRoute].
  ///
  /// The [child] argument must not be null.
23
  const WillPopScope({
24 25 26
    Key key,
    @required this.child,
    @required this.onWillPop,
27 28
  }) : assert(child != null),
       super(key: key);
29 30

  /// The widget below this widget in the tree.
31 32
  ///
  /// {@macro flutter.widgets.child}
33 34 35 36 37 38
  final Widget child;

  /// Called to veto attempts by the user to dismiss the enclosing [ModalRoute].
  ///
  /// If the callback returns a Future that resolves to false, the enclosing
  /// route will not be popped.
39
  final WillPopCallback onWillPop;
40 41 42 43 44 45 46 47 48

  @override
  _WillPopScopeState createState() => new _WillPopScopeState();
}

class _WillPopScopeState extends State<WillPopScope> {
  ModalRoute<dynamic> _route;

  @override
49 50
  void didChangeDependencies() {
    super.didChangeDependencies();
51 52
    if (widget.onWillPop != null)
      _route?.removeScopedWillPopCallback(widget.onWillPop);
53
    _route = ModalRoute.of(context);
54 55
    if (widget.onWillPop != null)
      _route?.addScopedWillPopCallback(widget.onWillPop);
56 57 58
  }

  @override
59
  void didUpdateWidget(WillPopScope oldWidget) {
60
    super.didUpdateWidget(oldWidget);
61
    assert(_route == ModalRoute.of(context));
62 63 64 65 66
    if (widget.onWillPop != oldWidget.onWillPop && _route != null) {
      if (oldWidget.onWillPop != null)
        _route.removeScopedWillPopCallback(oldWidget.onWillPop);
      if (widget.onWillPop != null)
        _route.addScopedWillPopCallback(widget.onWillPop);
67 68 69 70 71
    }
  }

  @override
  void dispose() {
72 73
    if (widget.onWillPop != null)
      _route?.removeScopedWillPopCallback(widget.onWillPop);
74 75 76 77
    super.dispose();
  }

  @override
78
  Widget build(BuildContext context) => widget.child;
79
}