Skip to content

Commit ffe14b0

Browse files
authored
Navigator.push and Navigator.pushNamed should return Futures (#6333)
These futures complete when the route is popped off the navigator. This generalizes and simplifies a mechanism already in place for dialogs and menus. Fixes #5283
1 parent cedbfd4 commit ffe14b0

12 files changed

Lines changed: 104 additions & 92 deletions

File tree

‎examples/flutter_gallery/lib/demo/shrine/shrine_home.dart‎

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -296,18 +296,10 @@ class _ShrineHomeState extends State<ShrineHome> {
296296
static final GlobalKey<ScrollableState> scrollableKey = new GlobalKey<ScrollableState>();
297297
static final GridDelegate gridDelegate = new ShrineGridDelegate();
298298

299-
void handleCompletedOrder(Order completedOrder) {
300-
assert(completedOrder.product != null);
301-
if (completedOrder.quantity == 0)
302-
_shoppingCart.remove(completedOrder.product);
303-
}
304-
305-
void showOrderPage(Product product) {
299+
Future<Null> showOrderPage(Product product) async {
306300
final Order order = _shoppingCart[product] ?? new Order(product: product);
307-
final Completer<Order> completer = new Completer<Order>();
308-
Navigator.push(context, new ShrineOrderRoute(
301+
final Order completedOrder = await Navigator.push(context, new ShrineOrderRoute(
309302
order: order,
310-
completer: completer,
311303
builder: (BuildContext context) {
312304
return new OrderPage(
313305
order: order,
@@ -316,7 +308,9 @@ class _ShrineHomeState extends State<ShrineHome> {
316308
);
317309
}
318310
));
319-
completer.future.then(handleCompletedOrder);
311+
assert(completedOrder.product != null);
312+
if (completedOrder.quantity == 0)
313+
_shoppingCart.remove(completedOrder.product);
320314
}
321315

322316
@override

‎examples/flutter_gallery/lib/demo/shrine/shrine_order.dart‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@
22
// Use of this source code is governed by a BSD-style license that can be
33
// found in the LICENSE file.
44

5-
import 'dart:async';
6-
75
import 'package:flutter/material.dart';
86

97
import '../shrine_demo.dart' show ShrinePageRoute;
@@ -226,9 +224,8 @@ class ShrineOrderRoute extends ShrinePageRoute<Order> {
226224
ShrineOrderRoute({
227225
this.order,
228226
WidgetBuilder builder,
229-
Completer<Order> completer,
230227
RouteSettings settings: const RouteSettings()
231-
}) : super(builder: builder, completer: completer, settings: settings) {
228+
}) : super(builder: builder, settings: settings) {
232229
assert(order != null);
233230
}
234231

‎examples/flutter_gallery/lib/demo/shrine_demo.dart‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@
22
// Use of this source code is governed by a BSD-style license that can be
33
// found in the LICENSE file.
44

5-
import 'dart:async';
6-
75
import 'package:flutter/material.dart';
86

97
import 'shrine/shrine_home.dart' show ShrineHome;
@@ -26,9 +24,8 @@ Widget buildShrine(Widget child) {
2624
class ShrinePageRoute<T> extends MaterialPageRoute<T> {
2725
ShrinePageRoute({
2826
WidgetBuilder builder,
29-
Completer<T> completer,
3027
RouteSettings settings: const RouteSettings()
31-
}) : super(builder: builder, completer: completer, settings: settings);
28+
}) : super(builder: builder, settings: settings);
3229

3330
@override
3431
Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> forwardAnimation) {

‎packages/flutter/lib/src/material/bottom_sheet.dart‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -204,10 +204,9 @@ class _ModalBottomSheetState<T> extends State<_ModalBottomSheet<T>> {
204204

205205
class _ModalBottomSheetRoute<T> extends PopupRoute<T> {
206206
_ModalBottomSheetRoute({
207-
Completer<T> completer,
208207
this.builder,
209208
this.theme,
210-
}) : super(completer: completer);
209+
});
211210

212211
final WidgetBuilder builder;
213212
final ThemeData theme;
@@ -260,11 +259,8 @@ class _ModalBottomSheetRoute<T> extends PopupRoute<T> {
260259
Future<dynamic/*=T*/> showModalBottomSheet/*<T>*/({ BuildContext context, WidgetBuilder builder }) {
261260
assert(context != null);
262261
assert(builder != null);
263-
final Completer<dynamic/*=T*/> completer = new Completer<dynamic/*=T*/>();
264-
Navigator.push(context, new _ModalBottomSheetRoute<dynamic/*=T*/>(
265-
completer: completer,
262+
return Navigator.push(context, new _ModalBottomSheetRoute<dynamic/*=T*/>(
266263
builder: builder,
267264
theme: Theme.of(context, shadowThemeOnly: true),
268265
));
269-
return completer.future;
270266
}

‎packages/flutter/lib/src/material/dialog.dart‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -278,10 +278,9 @@ class SimpleDialog extends StatelessWidget {
278278

279279
class _DialogRoute<T> extends PopupRoute<T> {
280280
_DialogRoute({
281-
Completer<T> completer,
282281
this.child,
283282
this.theme,
284-
}) : super(completer: completer);
283+
});
285284

286285
final Widget child;
287286
final ThemeData theme;
@@ -324,11 +323,8 @@ class _DialogRoute<T> extends PopupRoute<T> {
324323
/// * [Dialog]
325324
/// * <https://www.google.com/design/spec/components/dialogs.html>
326325
Future<dynamic/*=T*/> showDialog/*<T>*/({ BuildContext context, Widget child }) {
327-
Completer<dynamic/*=T*/> completer = new Completer<dynamic/*=T*/>();
328-
Navigator.push(context, new _DialogRoute<dynamic/*=T*/>(
329-
completer: completer,
326+
return Navigator.push(context, new _DialogRoute<dynamic/*=T*/>(
330327
child: child,
331328
theme: Theme.of(context, shadowThemeOnly: true),
332329
));
333-
return completer.future;
334330
}

‎packages/flutter/lib/src/material/drop_down.dart‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -288,14 +288,13 @@ class _DropdownRouteResult<T> {
288288

289289
class _DropdownRoute<T> extends PopupRoute<_DropdownRouteResult<T>> {
290290
_DropdownRoute({
291-
Completer<_DropdownRouteResult<T>> completer,
292291
this.items,
293292
this.buttonRect,
294293
this.selectedIndex,
295294
this.elevation: 8,
296295
this.theme,
297296
TextStyle style,
298-
}) : _style = style, super(completer: completer) {
297+
}) : _style = style {
299298
assert(style != null);
300299
}
301300

@@ -502,7 +501,6 @@ class _DropdownButtonState<T> extends State<DropdownButton<T>> {
502501
final Rect itemRect = itemBox.localToGlobal(Point.origin) & itemBox.size;
503502
final Completer<_DropdownRouteResult<T>> completer = new Completer<_DropdownRouteResult<T>>();
504503
_currentRoute = new _DropdownRoute<T>(
505-
completer: completer,
506504
items: config.items,
507505
buttonRect: _kMenuHorizontalPadding.inflateRect(itemRect),
508506
selectedIndex: _selectedIndex,

‎packages/flutter/lib/src/material/page.dart‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@
22
// Use of this source code is governed by a BSD-style license that can be
33
// found in the LICENSE file.
44

5-
import 'dart:async';
6-
75
import 'package:flutter/widgets.dart';
86
import 'material.dart';
97
import 'theme.dart';
@@ -167,10 +165,9 @@ class MaterialPageRoute<T> extends PageRoute<T> {
167165
/// Creates a page route for use in a material design app.
168166
MaterialPageRoute({
169167
this.builder,
170-
Completer<T> completer,
171168
RouteSettings settings: const RouteSettings(),
172169
this.maintainState: true,
173-
}) : super(completer: completer, settings: settings) {
170+
}) : super(settings: settings) {
174171
assert(builder != null);
175172
assert(opaque);
176173
}

‎packages/flutter/lib/src/material/popup_menu.dart‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -370,13 +370,12 @@ class _PopupMenuRouteLayout extends SingleChildLayoutDelegate {
370370

371371
class _PopupMenuRoute<T> extends PopupRoute<T> {
372372
_PopupMenuRoute({
373-
Completer<T> completer,
374373
this.position,
375374
this.items,
376375
this.initialValue,
377376
this.elevation,
378377
this.theme
379-
}) : super(completer: completer);
378+
});
380379

381380
final RelativeRect position;
382381
final List<PopupMenuEntry<T>> items;
@@ -439,16 +438,13 @@ Future<dynamic/*=T*/> showMenu/*<T>*/({
439438
}) {
440439
assert(context != null);
441440
assert(items != null && items.length > 0);
442-
Completer<dynamic/*=T*/> completer = new Completer<dynamic/*=T*/>();
443-
Navigator.push(context, new _PopupMenuRoute<dynamic/*=T*/>(
444-
completer: completer,
441+
return Navigator.push(context, new _PopupMenuRoute<dynamic/*=T*/>(
445442
position: position,
446443
items: items,
447444
initialValue: initialValue,
448445
elevation: elevation,
449446
theme: Theme.of(context, shadowThemeOnly: true),
450447
));
451-
return completer.future;
452448
}
453449

454450
/// A callback that is passed the value of the PopupMenuItem that caused

‎packages/flutter/lib/src/widgets/navigator.dart‎

Lines changed: 57 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
// Use of this source code is governed by a BSD-style license that can be
33
// found in the LICENSE file.
44

5+
import 'dart:async';
6+
57
import 'package:flutter/rendering.dart';
68
import 'package:meta/meta.dart';
79

@@ -32,6 +34,12 @@ abstract class Route<T> {
3234
/// will initialize its [Focus] to this key.
3335
GlobalKey get focusKey => null;
3436

37+
/// A future that completes when this route is popped off the navigator.
38+
///
39+
/// The future completes with the value given to [Navigator.pop], if any.
40+
Future<T> get popped => _popCompleter.future;
41+
final Completer<T> _popCompleter = new Completer<T>();
42+
3543
/// Called when the route is inserted into the navigator.
3644
///
3745
/// Use this to populate overlayEntries and add them to the overlay
@@ -40,16 +48,22 @@ abstract class Route<T> {
4048
/// responsible for _removing_ the entries and this way it's symmetric.)
4149
///
4250
/// The overlay argument will be null if this is the first route inserted.
51+
@protected
52+
@mustCallSuper
4353
void install(OverlayEntry insertionPoint) { }
4454

4555
/// Called after install() when the route is pushed onto the navigator.
56+
@protected
57+
@mustCallSuper
4658
void didPush() { }
4759

4860
/// When this route is popped (see [Navigator.pop]) if the result isn't
4961
/// specified or if it's null, this value will be used instead.
5062
T get currentResult => null;
5163

5264
/// Called after install() when the route replaced another in the navigator.
65+
@protected
66+
@mustCallSuper
5367
void didReplace(Route<dynamic> oldRoute) { }
5468

5569
/// A request was made to pop this route. If the route can handle it
@@ -59,26 +73,36 @@ abstract class Route<T> {
5973
///
6074
/// If this is called, the Navigator will not call dispose(). It is the
6175
/// responsibility of the Route to later call dispose().
62-
bool didPop(T result) => true;
76+
@protected
77+
@mustCallSuper
78+
bool didPop(T result) {
79+
_popCompleter.complete(result);
80+
return true;
81+
}
6382

6483
/// Whether calling didPop() would return false.
6584
bool get willHandlePopInternally => false;
6685

6786
/// The given route, which came after this one, has been popped off the
6887
/// navigator.
88+
@protected
89+
@mustCallSuper
6990
void didPopNext(Route<dynamic> nextRoute) { }
7091

7192
/// This route's next route has changed to the given new route. This is called
7293
/// on a route whenever the next route changes for any reason, except for
7394
/// cases when didPopNext() would be called, so long as it is in the history.
7495
/// nextRoute will be null if there's no next route.
96+
@protected
97+
@mustCallSuper
7598
void didChangeNext(Route<dynamic> nextRoute) { }
7699

77100
/// The route should remove its overlays and free any other resources.
78101
///
79102
/// A call to didPop() implies that the Route should call dispose() itself,
80103
/// but it is possible for dispose() to be called directly (e.g. if the route
81104
/// is replaced, or if the navigator itself is disposed).
105+
@mustCallSuper
82106
void dispose() { }
83107

84108
/// If the route's transition can be popped via a user gesture (e.g. the iOS
@@ -248,8 +272,10 @@ class Navigator extends StatefulWidget {
248272
///
249273
/// The route name will be passed to that navigator's [onGenerateRoute]
250274
/// callback. The returned route will be pushed into the navigator.
251-
static void pushNamed(BuildContext context, String routeName) {
252-
Navigator.of(context).pushNamed(routeName);
275+
///
276+
/// Returns a Future that completes when the pushed route is popped.
277+
static Future<dynamic> pushNamed(BuildContext context, String routeName) {
278+
return Navigator.of(context).pushNamed(routeName);
253279
}
254280

255281
/// Push a route onto the navigator that most tightly encloses the given context.
@@ -258,8 +284,10 @@ class Navigator extends StatefulWidget {
258284
/// The route will have didPush() and didChangeNext() called on it; the
259285
/// previous route, if any, will have didChangeNext() called on it; and the
260286
/// Navigator observer, if any, will have didPush() called on it.
261-
static void push(BuildContext context, Route<dynamic> route) {
262-
Navigator.of(context).push(route);
287+
///
288+
/// Returns a Future that completes when the pushed route is popped.
289+
static Future<dynamic> push(BuildContext context, Route<dynamic> route) {
290+
return Navigator.of(context).push(route);
263291
}
264292

265293
/// Pop a route off the navigator that most tightly encloses the given context.
@@ -269,10 +297,10 @@ class Navigator extends StatefulWidget {
269297
/// (if any) is notified using its didPop() method, and the previous route is
270298
/// notified using [Route.didChangeNext].
271299
///
272-
/// If non-null, [result] will be used as the result of the route. Routes
300+
/// If non-null, `result` will be used as the result of the route. Routes
273301
/// such as dialogs or popup menus typically use this mechanism to return the
274302
/// value selected by the user to the widget that created their route. The
275-
/// type of [result], if provided, must match the type argument of the class
303+
/// type of `result`, if provided, must match the type argument of the class
276304
/// of the current route. (In practice, this is usually "dynamic".)
277305
///
278306
/// Returns true if a route was popped; returns false if there are no further
@@ -299,11 +327,20 @@ class Navigator extends StatefulWidget {
299327
}
300328

301329
/// Executes a simple transaction that both pops the current route off and
302-
/// pushes a named route into the navigator that most tightly encloses the given context.
303-
static void popAndPushNamed(BuildContext context, String routeName) {
304-
Navigator.of(context)
305-
..pop()
306-
..pushNamed(routeName);
330+
/// pushes a named route into the navigator that most tightly encloses the
331+
/// given context.
332+
///
333+
/// If non-null, `result` will be used as the result of the route that is
334+
/// popped. Routes such as dialogs or popup menus typically use this mechanism
335+
/// to return the value selected by the user to the widget that created their
336+
/// route. The type of `result`, if provided, must match the type argument of
337+
/// the class of the current route. (In practice, this is usually "dynamic".)
338+
///
339+
/// Returns a Future that completes when the pushed route is popped.
340+
static Future<dynamic> popAndPushNamed(BuildContext context, String routeName, { dynamic result }) {
341+
NavigatorState navigator = Navigator.of(context);
342+
navigator.pop(result);
343+
return navigator.pushNamed(routeName);
307344
}
308345

309346
/// The state from the closest instance of this class that encloses the given context.
@@ -378,7 +415,9 @@ class NavigatorState extends State<Navigator> with TickerProviderStateMixin {
378415

379416
/// Looks up the route with the given name using [Navigator.onGenerateRoute],
380417
/// and then [push]es that route.
381-
void pushNamed(String name) {
418+
///
419+
/// Returns a Future that completes when the pushed route is popped.
420+
Future<dynamic> pushNamed(String name) {
382421
assert(!_debugLocked);
383422
assert(name != null);
384423
RouteSettings settings = new RouteSettings(name: name);
@@ -388,7 +427,7 @@ class NavigatorState extends State<Navigator> with TickerProviderStateMixin {
388427
route = config.onUnknownRoute(settings);
389428
assert(route != null);
390429
}
391-
push(route);
430+
return push(route);
392431
}
393432

394433
/// Adds the given route to the navigator's history, and transitions to it.
@@ -400,7 +439,9 @@ class NavigatorState extends State<Navigator> with TickerProviderStateMixin {
400439
///
401440
/// Ongoing gestures within the current route are canceled when a new route is
402441
/// pushed.
403-
void push(Route<dynamic> route) {
442+
///
443+
/// Returns a Future that completes when the pushed route is popped.
444+
Future<dynamic> push(Route<dynamic> route) {
404445
assert(!_debugLocked);
405446
assert(() { _debugLocked = true; return true; });
406447
assert(route != null);
@@ -418,6 +459,7 @@ class NavigatorState extends State<Navigator> with TickerProviderStateMixin {
418459
});
419460
assert(() { _debugLocked = false; return true; });
420461
_cancelActivePointers();
462+
return route.popped;
421463
}
422464

423465
/// Replaces a route that is not currently visible with a new route.

0 commit comments

Comments
 (0)