From de884f1afe1daa12def5ecaa08ab03e6af406d39 Mon Sep 17 00:00:00 2001 From: Greg Spencer Date: Fri, 20 Nov 2020 09:10:46 -0800 Subject: [PATCH] Remove the `nullOk` parameter from `Navigator.of` and add `Navigator.maybeOf` (#70726) Adds Navigator.maybeOf to replace calling Navigator.of(context, nullOk: true), and removes the nullOk parameter. Also changes Navigator.of to return a non-nullable value, and removes many (120!) instances of the ! operator, reducing the possible places where a null dereference could occur. --- .../cupertino/cupertino_navigation_demo.dart | 8 +- .../material/full_screen_dialog_demo.dart | 4 +- .../lib/demo/material/search_demo.dart | 2 +- .../demo/material/text_form_field_demo.dart | 4 +- .../lib/demo/shrine/login.dart | 4 +- .../transformations/transformations_demo.dart | 2 +- .../flutter_gallery/lib/demo/video_demo.dart | 2 +- .../lib/src/cupertino/context_menu.dart | 4 +- packages/flutter/lib/src/cupertino/route.dart | 2 +- packages/flutter/lib/src/material/about.dart | 8 +- .../lib/src/material/bottom_sheet.dart | 2 +- packages/flutter/lib/src/material/dialog.dart | 2 +- .../flutter/lib/src/material/dropdown.dart | 2 +- .../flutter/lib/src/material/popup_menu.dart | 4 +- packages/flutter/lib/src/material/search.dart | 4 +- .../flutter/lib/src/widgets/navigator.dart | 102 ++++++++++++------ packages/flutter/lib/src/widgets/routes.dart | 4 +- .../flutter/test/cupertino/route_test.dart | 2 +- .../flutter/test/cupertino/scaffold_test.dart | 4 +- packages/flutter/test/cupertino/tab_test.dart | 12 +-- packages/flutter/test/material/app_test.dart | 6 +- .../flutter/test/material/dialog_test.dart | 2 +- .../test/material/inherited_theme_test.dart | 42 ++++---- packages/flutter/test/material/page_test.dart | 4 +- .../material/page_transitions_theme_test.dart | 10 +- .../test/material/popup_menu_test.dart | 2 +- .../test/material/range_slider_test.dart | 4 +- .../flutter/test/material/slider_test.dart | 4 +- .../flutter/test/material/snack_bar_test.dart | 2 +- .../test/material/text_field_focus_test.dart | 2 +- .../flutter/test/material/will_pop_test.dart | 12 +-- .../test/widgets/focus_traversal_test.dart | 8 +- .../test/widgets/inherited_theme_test.dart | 4 +- .../flutter/test/widgets/navigator_test.dart | 92 ++++++++++++---- .../test/widgets/page_route_builder_test.dart | 4 +- .../flutter/test/widgets/routes_test.dart | 16 +-- 36 files changed, 243 insertions(+), 149 deletions(-) diff --git a/dev/integration_tests/flutter_gallery/lib/demo/cupertino/cupertino_navigation_demo.dart b/dev/integration_tests/flutter_gallery/lib/demo/cupertino/cupertino_navigation_demo.dart index 191e99b268..1b450b795c 100644 --- a/dev/integration_tests/flutter_gallery/lib/demo/cupertino/cupertino_navigation_demo.dart +++ b/dev/integration_tests/flutter_gallery/lib/demo/cupertino/cupertino_navigation_demo.dart @@ -117,7 +117,7 @@ class ExitButton extends StatelessWidget { ), onPressed: () { // The demo is on the root navigator. - Navigator.of(context, rootNavigator: true)!.pop(); + Navigator.of(context, rootNavigator: true).pop(); }, ); } @@ -202,7 +202,7 @@ class Tab1RowItem extends StatelessWidget { final Widget row = GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { - Navigator.of(context)!.push(CupertinoPageRoute( + Navigator.of(context).push(CupertinoPageRoute( title: colorName, builder: (BuildContext context) => Tab1ItemPage( color: color, @@ -752,7 +752,7 @@ class CupertinoDemoTab3 extends StatelessWidget { const Padding(padding: EdgeInsets.only(top: 32.0)), GestureDetector( onTap: () { - Navigator.of(context, rootNavigator: true)!.push( + Navigator.of(context, rootNavigator: true).push( CupertinoPageRoute( fullscreenDialog: true, builder: (BuildContext context) => Tab3Dialog(), @@ -800,7 +800,7 @@ class Tab3Dialog extends StatelessWidget { child: const Text('Cancel'), padding: EdgeInsets.zero, onPressed: () { - Navigator.of(context)!.pop(false); + Navigator.of(context).pop(false); }, ), ), diff --git a/dev/integration_tests/flutter_gallery/lib/demo/material/full_screen_dialog_demo.dart b/dev/integration_tests/flutter_gallery/lib/demo/material/full_screen_dialog_demo.dart index 5aefbec4ed..c53f505c63 100644 --- a/dev/integration_tests/flutter_gallery/lib/demo/material/full_screen_dialog_demo.dart +++ b/dev/integration_tests/flutter_gallery/lib/demo/material/full_screen_dialog_demo.dart @@ -126,13 +126,13 @@ class FullScreenDialogDemoState extends State { TextButton( child: const Text('CANCEL'), onPressed: () { - Navigator.of(context)!.pop(false); // Pops the confirmation dialog but not the page. + Navigator.of(context).pop(false); // Pops the confirmation dialog but not the page. }, ), TextButton( child: const Text('DISCARD'), onPressed: () { - Navigator.of(context)!.pop(true); // Returning true to _onWillPop will pop again. + Navigator.of(context).pop(true); // Returning true to _onWillPop will pop again. }, ), ], diff --git a/dev/integration_tests/flutter_gallery/lib/demo/material/search_demo.dart b/dev/integration_tests/flutter_gallery/lib/demo/material/search_demo.dart index d38d08096f..ee3cc975a5 100644 --- a/dev/integration_tests/flutter_gallery/lib/demo/material/search_demo.dart +++ b/dev/integration_tests/flutter_gallery/lib/demo/material/search_demo.dart @@ -98,7 +98,7 @@ class _SearchDemoState extends State { floatingActionButton: FloatingActionButton.extended( tooltip: 'Back', // Tests depend on this label to exit the demo. onPressed: () { - Navigator.of(context)!.pop(); + Navigator.of(context).pop(); }, label: const Text('Close demo'), icon: const Icon(Icons.close), diff --git a/dev/integration_tests/flutter_gallery/lib/demo/material/text_form_field_demo.dart b/dev/integration_tests/flutter_gallery/lib/demo/material/text_form_field_demo.dart index d65bf3e3cd..4e1241782a 100644 --- a/dev/integration_tests/flutter_gallery/lib/demo/material/text_form_field_demo.dart +++ b/dev/integration_tests/flutter_gallery/lib/demo/material/text_form_field_demo.dart @@ -151,11 +151,11 @@ class TextFormFieldDemoState extends State { actions: [ TextButton( child: const Text('YES'), - onPressed: () { Navigator.of(context)!.pop(true); }, + onPressed: () { Navigator.of(context).pop(true); }, ), TextButton( child: const Text('NO'), - onPressed: () { Navigator.of(context)!.pop(false); }, + onPressed: () { Navigator.of(context).pop(false); }, ), ], ); diff --git a/dev/integration_tests/flutter_gallery/lib/demo/shrine/login.dart b/dev/integration_tests/flutter_gallery/lib/demo/shrine/login.dart index 3061a41e7d..0e544538f8 100644 --- a/dev/integration_tests/flutter_gallery/lib/demo/shrine/login.dart +++ b/dev/integration_tests/flutter_gallery/lib/demo/shrine/login.dart @@ -35,7 +35,7 @@ class _LoginPageState extends State { // The login screen is immediately displayed on top of the Shrine // home screen using onGenerateRoute and so rootNavigator must be // set to true in order to get out of Shrine completely. - Navigator.of(context, rootNavigator: true)!.pop(); + Navigator.of(context, rootNavigator: true).pop(); }, ), ), @@ -95,7 +95,7 @@ class _LoginPageState extends State { // the Shrine home screen using onGenerateRoute and so // rootNavigator must be set to true in order to get out // of Shrine completely. - Navigator.of(context, rootNavigator: true)!.pop(); + Navigator.of(context, rootNavigator: true).pop(); }, child: const Text('CANCEL'), ), diff --git a/dev/integration_tests/flutter_gallery/lib/demo/transformations/transformations_demo.dart b/dev/integration_tests/flutter_gallery/lib/demo/transformations/transformations_demo.dart index 0f4e88eaab..f325b24cf8 100644 --- a/dev/integration_tests/flutter_gallery/lib/demo/transformations/transformations_demo.dart +++ b/dev/integration_tests/flutter_gallery/lib/demo/transformations/transformations_demo.dart @@ -107,7 +107,7 @@ class _TransformationsDemoState extends State { TextButton( child: const Text('OK'), onPressed: () { - Navigator.of(context)!.pop(); + Navigator.of(context).pop(); }, ), ], diff --git a/dev/integration_tests/flutter_gallery/lib/demo/video_demo.dart b/dev/integration_tests/flutter_gallery/lib/demo/video_demo.dart index 5639fe4c60..485117ffbe 100644 --- a/dev/integration_tests/flutter_gallery/lib/demo/video_demo.dart +++ b/dev/integration_tests/flutter_gallery/lib/demo/video_demo.dart @@ -70,7 +70,7 @@ class VideoCard extends StatelessWidget { }); controller!.setVolume(1.0); - Navigator.of(context)!.push(route); + Navigator.of(context).push(route); } return SafeArea( diff --git a/packages/flutter/lib/src/cupertino/context_menu.dart b/packages/flutter/lib/src/cupertino/context_menu.dart index f6b509a9d6..169ef22289 100644 --- a/packages/flutter/lib/src/cupertino/context_menu.dart +++ b/packages/flutter/lib/src/cupertino/context_menu.dart @@ -292,7 +292,7 @@ class _CupertinoContextMenuState extends State with Ticker return widget.previewBuilder!(context, animation, widget.child); }, ); - Navigator.of(context, rootNavigator: true)!.push(_route!); + Navigator.of(context, rootNavigator: true).push(_route!); _route!.animation!.addStatusListener(_routeAnimationStatusListener); } @@ -686,7 +686,7 @@ class _ContextMenuRoute extends PopupRoute { parent: animation!, curve: const Interval(0.9, 1.0), )); - Navigator.of(context)!.pop(); + Navigator.of(context).pop(); } // Take measurements on the child and _ContextMenuSheet and update the diff --git a/packages/flutter/lib/src/cupertino/route.dart b/packages/flutter/lib/src/cupertino/route.dart index 71ac2e6952..5d62acfb5a 100644 --- a/packages/flutter/lib/src/cupertino/route.dart +++ b/packages/flutter/lib/src/cupertino/route.dart @@ -1060,7 +1060,7 @@ Future showCupertinoModalPopup({ RouteSettings? routeSettings, }) { assert(useRootNavigator != null); - return Navigator.of(context, rootNavigator: useRootNavigator)!.push( + return Navigator.of(context, rootNavigator: useRootNavigator).push( _CupertinoModalPopupRoute( barrierColor: CupertinoDynamicColor.resolve(barrierColor, context), barrierDismissible: barrierDismissible, diff --git a/packages/flutter/lib/src/material/about.dart b/packages/flutter/lib/src/material/about.dart index 6cc88b0512..d71c08e86e 100644 --- a/packages/flutter/lib/src/material/about.dart +++ b/packages/flutter/lib/src/material/about.dart @@ -292,7 +292,7 @@ void showLicensePage({ }) { assert(context != null); assert(useRootNavigator != null); - Navigator.of(context, rootNavigator: useRootNavigator)!.push(MaterialPageRoute( + Navigator.of(context, rootNavigator: useRootNavigator).push(MaterialPageRoute( builder: (BuildContext context) => LicensePage( applicationName: applicationName, applicationVersion: applicationVersion, @@ -1342,8 +1342,8 @@ class _MasterDetailFlowState extends State<_MasterDetailFlow> implements _PageOp ? widget.masterPageBuilder!(c, false) : _MasterPage( leading: widget.leading ?? - (widget.automaticallyImplyLeading && Navigator.of(context)!.canPop() - ? BackButton(onPressed: () => Navigator.of(context)!.pop()) + (widget.automaticallyImplyLeading && Navigator.of(context).canPop() + ? BackButton(onPressed: () => Navigator.of(context).pop()) : null), title: widget.title, centerTitle: widget.centerTitle, @@ -1364,7 +1364,7 @@ class _MasterDetailFlowState extends State<_MasterDetailFlow> implements _PageOp onWillPop: () async { // No need for setState() as rebuild happens on navigation pop. focus = _Focus.master; - Navigator.of(context)!.pop(); + Navigator.of(context).pop(); return false; }, child: BlockSemantics(child: widget.detailPageBuilder(context, arguments, null)), diff --git a/packages/flutter/lib/src/material/bottom_sheet.dart b/packages/flutter/lib/src/material/bottom_sheet.dart index 36fa37f197..2137909436 100644 --- a/packages/flutter/lib/src/material/bottom_sheet.dart +++ b/packages/flutter/lib/src/material/bottom_sheet.dart @@ -669,7 +669,7 @@ Future showModalBottomSheet({ assert(debugCheckHasMediaQuery(context)); assert(debugCheckHasMaterialLocalizations(context)); - final NavigatorState navigator = Navigator.of(context, rootNavigator: useRootNavigator)!; + final NavigatorState navigator = Navigator.of(context, rootNavigator: useRootNavigator); return navigator.push(_ModalBottomSheetRoute( builder: builder, capturedThemes: InheritedTheme.capture(from: context, to: navigator.context), diff --git a/packages/flutter/lib/src/material/dialog.dart b/packages/flutter/lib/src/material/dialog.dart index 290c6fa7a5..537a780171 100644 --- a/packages/flutter/lib/src/material/dialog.dart +++ b/packages/flutter/lib/src/material/dialog.dart @@ -978,7 +978,7 @@ Future showDialog({ assert(useRootNavigator != null); assert(debugCheckHasMaterialLocalizations(context)); - final CapturedThemes themes = InheritedTheme.capture(from: context, to: Navigator.of(context, rootNavigator: useRootNavigator)!.context); + final CapturedThemes themes = InheritedTheme.capture(from: context, to: Navigator.of(context, rootNavigator: useRootNavigator).context); return showGeneralDialog( context: context, pageBuilder: (BuildContext buildContext, Animation animation, Animation secondaryAnimation) { diff --git a/packages/flutter/lib/src/material/dropdown.dart b/packages/flutter/lib/src/material/dropdown.dart index 22f2768c6b..681cb3ec8c 100644 --- a/packages/flutter/lib/src/material/dropdown.dart +++ b/packages/flutter/lib/src/material/dropdown.dart @@ -1206,7 +1206,7 @@ class _DropdownButtonState extends State> with WidgetsBindi ) ]; - final NavigatorState navigator = Navigator.of(context)!; + final NavigatorState navigator = Navigator.of(context); assert(_dropdownRoute == null); _dropdownRoute = _DropdownRoute( items: menuItems, diff --git a/packages/flutter/lib/src/material/popup_menu.dart b/packages/flutter/lib/src/material/popup_menu.dart index 8b1fc021e4..5b298d712f 100644 --- a/packages/flutter/lib/src/material/popup_menu.dart +++ b/packages/flutter/lib/src/material/popup_menu.dart @@ -842,7 +842,7 @@ Future showMenu({ semanticLabel ??= MaterialLocalizations.of(context).popupMenuLabel; } - final NavigatorState navigator = Navigator.of(context, rootNavigator: useRootNavigator)!; + final NavigatorState navigator = Navigator.of(context, rootNavigator: useRootNavigator); return navigator.push(_PopupMenuRoute( position: position, items: items, @@ -1060,7 +1060,7 @@ class PopupMenuButtonState extends State> { void showButtonMenu() { final PopupMenuThemeData popupMenuTheme = PopupMenuTheme.of(context); final RenderBox button = context.findRenderObject()! as RenderBox; - final RenderBox overlay = Navigator.of(context)!.overlay!.context.findRenderObject()! as RenderBox; + final RenderBox overlay = Navigator.of(context).overlay!.context.findRenderObject()! as RenderBox; final RelativeRect position = RelativeRect.fromRect( Rect.fromPoints( button.localToGlobal(widget.offset, ancestor: overlay), diff --git a/packages/flutter/lib/src/material/search.dart b/packages/flutter/lib/src/material/search.dart index 3d8475caa5..77b8f600f0 100644 --- a/packages/flutter/lib/src/material/search.dart +++ b/packages/flutter/lib/src/material/search.dart @@ -60,7 +60,7 @@ Future showSearch({ assert(context != null); delegate.query = query ?? delegate.query; delegate._currentBody = _SearchBody.suggestions; - return Navigator.of(context)!.push(_SearchPageRoute( + return Navigator.of(context).push(_SearchPageRoute( delegate: delegate, )); } @@ -294,7 +294,7 @@ abstract class SearchDelegate { void close(BuildContext context, T result) { _currentBody = null; _focusNode?.unfocus(); - Navigator.of(context)! + Navigator.of(context) ..popUntil((Route route) => route == _route) ..pop(result); } diff --git a/packages/flutter/lib/src/widgets/navigator.dart b/packages/flutter/lib/src/widgets/navigator.dart index 45a7ce093b..5a13343357 100644 --- a/packages/flutter/lib/src/widgets/navigator.dart +++ b/packages/flutter/lib/src/widgets/navigator.dart @@ -1702,7 +1702,7 @@ class Navigator extends StatefulWidget { String routeName, { Object? arguments, }) { - return Navigator.of(context)!.pushNamed(routeName, arguments: arguments); + return Navigator.of(context).pushNamed(routeName, arguments: arguments); } /// Push a named route onto the navigator that most tightly encloses the given @@ -1757,7 +1757,7 @@ class Navigator extends StatefulWidget { String routeName, { Object? arguments, }) { - return Navigator.of(context)!.restorablePushNamed(routeName, arguments: arguments); + return Navigator.of(context).restorablePushNamed(routeName, arguments: arguments); } /// Replace the current route of the navigator that most tightly encloses the @@ -1820,7 +1820,7 @@ class Navigator extends StatefulWidget { TO? result, Object? arguments, }) { - return Navigator.of(context)!.pushReplacementNamed(routeName, arguments: arguments, result: result); + return Navigator.of(context).pushReplacementNamed(routeName, arguments: arguments, result: result); } /// Replace the current route of the navigator that most tightly encloses the @@ -1856,7 +1856,7 @@ class Navigator extends StatefulWidget { TO? result, Object? arguments, }) { - return Navigator.of(context)!.restorablePushReplacementNamed(routeName, arguments: arguments, result: result); + return Navigator.of(context).restorablePushReplacementNamed(routeName, arguments: arguments, result: result); } /// Pop the current route off the navigator that most tightly encloses the @@ -1914,7 +1914,7 @@ class Navigator extends StatefulWidget { TO? result, Object? arguments, }) { - return Navigator.of(context)!.popAndPushNamed(routeName, arguments: arguments, result: result); + return Navigator.of(context).popAndPushNamed(routeName, arguments: arguments, result: result); } /// Pop the current route off the navigator that most tightly encloses the @@ -1949,7 +1949,7 @@ class Navigator extends StatefulWidget { TO? result, Object? arguments, }) { - return Navigator.of(context)!.restorablePopAndPushNamed(routeName, arguments: arguments, result: result); + return Navigator.of(context).restorablePopAndPushNamed(routeName, arguments: arguments, result: result); } /// Push the route with the given name onto the navigator that most tightly @@ -2018,7 +2018,7 @@ class Navigator extends StatefulWidget { RoutePredicate predicate, { Object? arguments, }) { - return Navigator.of(context)!.pushNamedAndRemoveUntil(newRouteName, predicate, arguments: arguments); + return Navigator.of(context).pushNamedAndRemoveUntil(newRouteName, predicate, arguments: arguments); } /// Push the route with the given name onto the navigator that most tightly @@ -2054,7 +2054,7 @@ class Navigator extends StatefulWidget { RoutePredicate predicate, { Object? arguments, }) { - return Navigator.of(context)!.restorablePushNamedAndRemoveUntil(newRouteName, predicate, arguments: arguments); + return Navigator.of(context).restorablePushNamedAndRemoveUntil(newRouteName, predicate, arguments: arguments); } /// Push the given route onto the navigator that most tightly encloses the @@ -2092,7 +2092,7 @@ class Navigator extends StatefulWidget { /// state restoration. @optionalTypeArgs static Future push(BuildContext context, Route route) { - return Navigator.of(context)!.push(route); + return Navigator.of(context).push(route); } /// Push a new route onto the navigator that most tightly encloses the @@ -2146,7 +2146,7 @@ class Navigator extends StatefulWidget { /// {@end-tool} @optionalTypeArgs static String restorablePush(BuildContext context, RestorableRouteBuilder routeBuilder, {Object? arguments}) { - return Navigator.of(context)!.restorablePush(routeBuilder, arguments: arguments); + return Navigator.of(context).restorablePush(routeBuilder, arguments: arguments); } /// Replace the current route of the navigator that most tightly encloses the @@ -2195,7 +2195,7 @@ class Navigator extends StatefulWidget { /// be restored during state restoration. @optionalTypeArgs static Future pushReplacement(BuildContext context, Route newRoute, { TO? result }) { - return Navigator.of(context)!.pushReplacement(newRoute, result: result); + return Navigator.of(context).pushReplacement(newRoute, result: result); } /// Replace the current route of the navigator that most tightly encloses the @@ -2241,7 +2241,7 @@ class Navigator extends StatefulWidget { /// {@end-tool} @optionalTypeArgs static String restorablePushReplacement(BuildContext context, RestorableRouteBuilder routeBuilder, { TO? result, Object? arguments }) { - return Navigator.of(context)!.restorablePushReplacement(routeBuilder, result: result, arguments: arguments); + return Navigator.of(context).restorablePushReplacement(routeBuilder, result: result, arguments: arguments); } /// Push the given route onto the navigator that most tightly encloses the @@ -2300,7 +2300,7 @@ class Navigator extends StatefulWidget { /// restored during state restoration. @optionalTypeArgs static Future pushAndRemoveUntil(BuildContext context, Route newRoute, RoutePredicate predicate) { - return Navigator.of(context)!.pushAndRemoveUntil(newRoute, predicate); + return Navigator.of(context).pushAndRemoveUntil(newRoute, predicate); } /// Push a new route onto the navigator that most tightly encloses the @@ -2350,7 +2350,7 @@ class Navigator extends StatefulWidget { /// {@end-tool} @optionalTypeArgs static String restorablePushAndRemoveUntil(BuildContext context, RestorableRouteBuilder newRouteBuilder, RoutePredicate predicate, {Object? arguments}) { - return Navigator.of(context)!.restorablePushAndRemoveUntil(newRouteBuilder, predicate, arguments: arguments); + return Navigator.of(context).restorablePushAndRemoveUntil(newRouteBuilder, predicate, arguments: arguments); } /// Replaces a route on the navigator that most tightly encloses the given @@ -2388,7 +2388,7 @@ class Navigator extends StatefulWidget { /// restored during state restoration. @optionalTypeArgs static void replace(BuildContext context, { required Route oldRoute, required Route newRoute }) { - return Navigator.of(context)!.replace(oldRoute: oldRoute, newRoute: newRoute); + return Navigator.of(context).replace(oldRoute: oldRoute, newRoute: newRoute); } /// Replaces a route on the navigator that most tightly encloses the given @@ -2407,7 +2407,7 @@ class Navigator extends StatefulWidget { /// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue} @optionalTypeArgs static String restorableReplace(BuildContext context, { required Route oldRoute, required RestorableRouteBuilder newRouteBuilder, Object? arguments }) { - return Navigator.of(context)!.restorableReplace(oldRoute: oldRoute, newRouteBuilder: newRouteBuilder, arguments: arguments); + return Navigator.of(context).restorableReplace(oldRoute: oldRoute, newRouteBuilder: newRouteBuilder, arguments: arguments); } /// Replaces a route on the navigator that most tightly encloses the given @@ -2443,7 +2443,7 @@ class Navigator extends StatefulWidget { /// be restored during state restoration. @optionalTypeArgs static void replaceRouteBelow(BuildContext context, { required Route anchorRoute, required Route newRoute }) { - return Navigator.of(context)!.replaceRouteBelow(anchorRoute: anchorRoute, newRoute: newRoute); + return Navigator.of(context).replaceRouteBelow(anchorRoute: anchorRoute, newRoute: newRoute); } /// Replaces a route on the navigator that most tightly encloses the given @@ -2463,7 +2463,7 @@ class Navigator extends StatefulWidget { /// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue} @optionalTypeArgs static String restorableReplaceRouteBelow(BuildContext context, { required Route anchorRoute, required RestorableRouteBuilder newRouteBuilder, Object? arguments }) { - return Navigator.of(context)!.restorableReplaceRouteBelow(anchorRoute: anchorRoute, newRouteBuilder: newRouteBuilder, arguments: arguments); + return Navigator.of(context).restorableReplaceRouteBelow(anchorRoute: anchorRoute, newRouteBuilder: newRouteBuilder, arguments: arguments); } /// Whether the navigator that most tightly encloses the given context can be @@ -2482,7 +2482,7 @@ class Navigator extends StatefulWidget { /// * [Route.isFirst], which returns true for routes for which [canPop] /// returns false. static bool canPop(BuildContext context) { - final NavigatorState? navigator = Navigator.of(context, nullOk: true); + final NavigatorState? navigator = Navigator.maybeOf(context); return navigator != null && navigator.canPop(); } @@ -2518,7 +2518,7 @@ class Navigator extends StatefulWidget { /// to define the route's `willPop` method. @optionalTypeArgs static Future maybePop(BuildContext context, [ T? result ]) { - return Navigator.of(context)!.maybePop(result); + return Navigator.of(context).maybePop(result); } /// Pop the top-most route off the navigator that most tightly encloses the @@ -2568,7 +2568,7 @@ class Navigator extends StatefulWidget { /// ``` @optionalTypeArgs static void pop(BuildContext context, [ T? result ]) { - Navigator.of(context)!.pop(result); + Navigator.of(context).pop(result); } /// Calls [pop] repeatedly on the navigator that most tightly encloses the @@ -2597,7 +2597,7 @@ class Navigator extends StatefulWidget { /// ``` /// {@end-tool} static void popUntil(BuildContext context, RoutePredicate predicate) { - Navigator.of(context)!.popUntil(predicate); + Navigator.of(context).popUntil(predicate); } /// Immediately remove `route` from the navigator that most tightly encloses @@ -2624,7 +2624,7 @@ class Navigator extends StatefulWidget { /// This method is used, for example, to instantly dismiss dropdown menus that /// are up when the screen's orientation changes. static void removeRoute(BuildContext context, Route route) { - return Navigator.of(context)!.removeRoute(route); + return Navigator.of(context).removeRoute(route); } /// Immediately remove a route from the navigator that most tightly encloses @@ -2649,10 +2649,11 @@ class Navigator extends StatefulWidget { /// Ongoing gestures within the current route are canceled. /// {@endtemplate} static void removeRouteBelow(BuildContext context, Route anchorRoute) { - return Navigator.of(context)!.removeRouteBelow(anchorRoute); + return Navigator.of(context).removeRouteBelow(anchorRoute); } - /// The state from the closest instance of this class that encloses the given context. + /// The state from the closest instance of this class that encloses the given + /// context. /// /// Typical usage is as follows: /// @@ -2664,12 +2665,14 @@ class Navigator extends StatefulWidget { /// ``` /// /// If `rootNavigator` is set to true, the state from the furthest instance of - /// this class is given instead. Useful for pushing contents above all subsequent - /// instances of [Navigator]. - static NavigatorState? of( + /// this class is given instead. Useful for pushing contents above all + /// subsequent instances of [Navigator]. + /// + /// If there is no [Navigator] in the give `context`, this function will throw + /// a [FlutterError] in debug mode, and an exception in release mode. + static NavigatorState of( BuildContext context, { bool rootNavigator = false, - bool nullOk = false, }) { // Handles the case where the input context is a navigator element. NavigatorState? navigator; @@ -2683,7 +2686,7 @@ class Navigator extends StatefulWidget { } assert(() { - if (navigator == null && !nullOk) { + if (navigator == null) { throw FlutterError( 'Navigator operation requested with a context that does not include a Navigator.\n' 'The context used to push or pop routes from the Navigator must be that of a ' @@ -2692,6 +2695,43 @@ class Navigator extends StatefulWidget { } return true; }()); + return navigator!; + } + + /// The state from the closest instance of this class that encloses the given + /// context, if any. + /// + /// Typical usage is as follows: + /// + /// ```dart + /// NavigatorState? navigatorState = Navigator.maybeOf(context); + /// if (navigatorState != null) { + /// navigatorState + /// ..pop() + /// ..pop() + /// ..pushNamed('/settings'); + /// } + /// ``` + /// + /// If `rootNavigator` is set to true, the state from the furthest instance of + /// this class is given instead. Useful for pushing contents above all + /// subsequent instances of [Navigator]. + /// + /// Will return null if there is no ancestor [Navigator] in the `context`. + static NavigatorState? maybeOf( + BuildContext context, { + bool rootNavigator = false, + }) { + // Handles the case where the input context is a navigator element. + NavigatorState? navigator; + if (context is StatefulElement && context.state is NavigatorState) { + navigator = context.state as NavigatorState; + } + if (rootNavigator) { + navigator = context.findRootAncestorStateOfType() ?? navigator; + } else { + navigator = navigator ?? context.findAncestorStateOfType(); + } return navigator; } @@ -5767,5 +5807,5 @@ class RestorableRouteFuture extends RestorableProperty { }); } - static NavigatorState _defaultNavigatorFinder(BuildContext context) => Navigator.of(context, nullOk: false)!; + static NavigatorState _defaultNavigatorFinder(BuildContext context) => Navigator.of(context); } diff --git a/packages/flutter/lib/src/widgets/routes.dart b/packages/flutter/lib/src/widgets/routes.dart index 4cc31216fb..197fd3d9be 100644 --- a/packages/flutter/lib/src/widgets/routes.dart +++ b/packages/flutter/lib/src/widgets/routes.dart @@ -664,7 +664,7 @@ class _DismissModalAction extends DismissAction { @override Object invoke(DismissIntent intent) { - return Navigator.of(context)!.maybePop(); + return Navigator.of(context).maybePop(); } } @@ -1849,7 +1849,7 @@ Future showGeneralDialog({ assert(pageBuilder != null); assert(useRootNavigator != null); assert(!barrierDismissible || barrierLabel != null); - return Navigator.of(context, rootNavigator: useRootNavigator)!.push(_DialogRoute( + return Navigator.of(context, rootNavigator: useRootNavigator).push(_DialogRoute( pageBuilder: pageBuilder, barrierDismissible: barrierDismissible, barrierLabel: barrierLabel, diff --git a/packages/flutter/test/cupertino/route_test.dart b/packages/flutter/test/cupertino/route_test.dart index 682f078b06..6b9a4d41ed 100644 --- a/packages/flutter/test/cupertino/route_test.dart +++ b/packages/flutter/test/cupertino/route_test.dart @@ -1652,7 +1652,7 @@ void main() { return RaisedButton( child: const Text('Home'), onPressed: () { - navigator = Navigator.of(context)!; + navigator = Navigator.of(context); assert(navigator != null); navigator.push(r); }, diff --git a/packages/flutter/test/cupertino/scaffold_test.dart b/packages/flutter/test/cupertino/scaffold_test.dart index dc09eee3e1..7f86ece9d0 100644 --- a/packages/flutter/test/cupertino/scaffold_test.dart +++ b/packages/flutter/test/cupertino/scaffold_test.dart @@ -322,7 +322,7 @@ void main() { child: CupertinoButton( child: const Text('Next'), onPressed: () { - Navigator.of(context)!.push( + Navigator.of(context).push( CupertinoPageRoute( builder: (BuildContext context) { return CupertinoPageScaffold( @@ -333,7 +333,7 @@ void main() { child: CupertinoButton( child: const Text('Back'), onPressed: () { - Navigator.of(context)!.pop(); + Navigator.of(context).pop(); }, ), ), diff --git a/packages/flutter/test/cupertino/tab_test.dart b/packages/flutter/test/cupertino/tab_test.dart index 495b4191a4..2cd170a534 100644 --- a/packages/flutter/test/cupertino/tab_test.dart +++ b/packages/flutter/test/cupertino/tab_test.dart @@ -40,7 +40,7 @@ void main() { return CupertinoButton( child: const Text('go to second page'), onPressed: () { - Navigator.of(context)!.pushNamed('/2'); + Navigator.of(context).pushNamed('/2'); }, ); }, @@ -131,7 +131,7 @@ void main() { return CupertinoButton( child: const Text('go to second page'), onPressed: () { - Navigator.of(context)!.pushNamed('/2'); + Navigator.of(context).pushNamed('/2'); }, ); }, @@ -156,7 +156,7 @@ void main() { return CupertinoButton( child: const Text('go to second page'), onPressed: () { - Navigator.of(context)!.pushNamed('/2'); + Navigator.of(context).pushNamed('/2'); }, ); }, @@ -245,7 +245,7 @@ void main() { builder: (BuildContext context) => CupertinoButton( child: const Text('home'), onPressed: () { - Navigator.of(context)!.restorablePushNamed('/2'); + Navigator.of(context).restorablePushNamed('/2'); }, ), routes: { @@ -269,7 +269,7 @@ void main() { expect(find.text('home'), findsNothing); expect(find.text('second route'), findsOneWidget); - Navigator.of(tester.element(find.text('second route')))!.pop(); + Navigator.of(tester.element(find.text('second route'))).pop(); await tester.pumpAndSettle(); expect(find.text('home'), findsOneWidget); @@ -280,7 +280,7 @@ void main() { expect(find.text('home'), findsNothing); expect(find.text('second route'), findsOneWidget); - Navigator.of(tester.element(find.text('second route')))!.pop(); + Navigator.of(tester.element(find.text('second route'))).pop(); await tester.pumpAndSettle(); expect(find.text('home'), findsOneWidget); diff --git a/packages/flutter/test/material/app_test.dart b/packages/flutter/test/material/app_test.dart index 7d2d6284c4..69f974e187 100644 --- a/packages/flutter/test/material/app_test.dart +++ b/packages/flutter/test/material/app_test.dart @@ -100,7 +100,7 @@ void main() { return Material( child: ElevatedButton( child: const Text('X'), - onPressed: () { Navigator.of(context)!.pushNamed('/next'); }, + onPressed: () { Navigator.of(context).pushNamed('/next'); }, ), ); } @@ -258,7 +258,7 @@ void main() { child: ElevatedButton( child: const Text('X'), onPressed: () async { - result = Navigator.of(context)!.pushNamed('/a'); + result = Navigator.of(context).pushNamed('/a'); }, ), ); @@ -270,7 +270,7 @@ void main() { child: ElevatedButton( child: const Text('Y'), onPressed: () { - Navigator.of(context)!.pop('all done'); + Navigator.of(context).pop('all done'); }, ), ); diff --git a/packages/flutter/test/material/dialog_test.dart b/packages/flutter/test/material/dialog_test.dart index c22e922dd9..646f3fd7bb 100644 --- a/packages/flutter/test/material/dialog_test.dart +++ b/packages/flutter/test/material/dialog_test.dart @@ -1813,7 +1813,7 @@ void main() { SimpleDialogOption( child: const Text('X'), onPressed: () { - Navigator.of(context)!.pop(); + Navigator.of(context).pop(); }, ), ], diff --git a/packages/flutter/test/material/inherited_theme_test.dart b/packages/flutter/test/material/inherited_theme_test.dart index 03df6a534f..f83918a378 100644 --- a/packages/flutter/test/material/inherited_theme_test.dart +++ b/packages/flutter/test/material/inherited_theme_test.dart @@ -41,7 +41,7 @@ void main() { ElevatedButton( child: const Text('push unwrapped'), onPressed: () { - Navigator.of(context)!.push( + Navigator.of(context).push( MaterialPageRoute( // The primaryBox will see the default Theme when built. builder: (BuildContext _) => primaryBox, @@ -52,7 +52,7 @@ void main() { ElevatedButton( child: const Text('push wrapped'), onPressed: () { - Navigator.of(context)!.push( + Navigator.of(context).push( MaterialPageRoute( // Capture the shadow Theme. builder: (BuildContext _) => InheritedTheme.captureAll(context, primaryBox), @@ -84,7 +84,7 @@ void main() { await tester.pumpAndSettle(); // route animation expect(containerColor(), primaryColor); - Navigator.of(navigatorContext)!.pop(); + Navigator.of(navigatorContext).pop(); await tester.pumpAndSettle(); // route animation // Show the route which contains primaryBox @@ -181,7 +181,7 @@ void main() { ElevatedButton( child: const Text('push unwrapped'), onPressed: () { - Navigator.of(context)!.push( + Navigator.of(context).push( MaterialPageRoute( // The Banner will see the default BannerTheme when built. builder: (BuildContext _) => banner, @@ -192,7 +192,7 @@ void main() { ElevatedButton( child: const Text('push wrapped'), onPressed: () { - Navigator.of(context)!.push( + Navigator.of(context).push( MaterialPageRoute( // Capture the shadow BannerTheme. builder: (BuildContext _) => InheritedTheme.captureAll(context, banner), @@ -234,7 +234,7 @@ void main() { expect(getTextStyle('hello').fontSize, bannerFontSize); expect(getTextStyle('hello').color, bannerTextColor); - Navigator.of(navigatorContext)!.pop(); + Navigator.of(navigatorContext).pop(); await tester.pumpAndSettle(); // route animation await tester.tap(find.text('push unwrapped')); @@ -271,7 +271,7 @@ void main() { ElevatedButton( child: const Text('push unwrapped'), onPressed: () { - Navigator.of(context)!.push( + Navigator.of(context).push( MaterialPageRoute( // The Banner will see the default BannerTheme when built. builder: (BuildContext _) => divider, @@ -282,7 +282,7 @@ void main() { ElevatedButton( child: const Text('push wrapped'), onPressed: () { - Navigator.of(context)!.push( + Navigator.of(context).push( MaterialPageRoute( // Capture the shadow BannerTheme. builder: (BuildContext _) => InheritedTheme.captureAll(context, divider), @@ -316,7 +316,7 @@ void main() { expect(dividerBorder().color, dividerColor); expect(dividerBorder().width, dividerThickness); - Navigator.of(navigatorContext)!.pop(); + Navigator.of(navigatorContext).pop(); await tester.pumpAndSettle(); // route animation await tester.tap(find.text('push unwrapped')); @@ -375,7 +375,7 @@ void main() { ElevatedButton( child: const Text('push unwrapped'), onPressed: () { - Navigator.of(context)!.push( + Navigator.of(context).push( MaterialPageRoute( // The Banner will see the default BannerTheme when built. builder: (BuildContext _) => listTiles, @@ -386,7 +386,7 @@ void main() { ElevatedButton( child: const Text('push wrapped'), onPressed: () { - Navigator.of(context)!.push( + Navigator.of(context).push( MaterialPageRoute( // Capture the shadow BannerTheme. builder: (BuildContext _) => InheritedTheme.captureAll(context, listTiles), @@ -429,7 +429,7 @@ void main() { expect(getIconStyle(selectedIconKey).color, tileSelectedColor); expect(getIconStyle(unselectedIconKey).color, tileIconColor); - Navigator.of(navigatorContext)!.pop(); + Navigator.of(navigatorContext).pop(); await tester.pumpAndSettle(); // route animation await tester.tap(find.text('push unwrapped')); @@ -475,7 +475,7 @@ void main() { ElevatedButton( child: const Text('push unwrapped'), onPressed: () { - Navigator.of(context)!.push( + Navigator.of(context).push( MaterialPageRoute( // The slider will see the default SliderTheme when built. builder: (BuildContext _) => slider, @@ -486,7 +486,7 @@ void main() { ElevatedButton( child: const Text('push wrapped'), onPressed: () { - Navigator.of(context)!.push( + Navigator.of(context).push( MaterialPageRoute( // Capture the shadow SliderTheme. builder: (BuildContext _) => InheritedTheme.captureAll(context, slider), @@ -513,7 +513,7 @@ void main() { expect(sliderBox, paints..rrect(color: activeTrackColor)..rrect(color: inactiveTrackColor)); expect(sliderBox, paints..circle(color: thumbColor)); - Navigator.of(navigatorContext)!.pop(); + Navigator.of(navigatorContext).pop(); await tester.pumpAndSettle(); // route animation await tester.tap(find.text('push unwrapped')); @@ -560,7 +560,7 @@ void main() { ElevatedButton( child: const Text('push unwrapped'), onPressed: () { - Navigator.of(context)!.push( + Navigator.of(context).push( MaterialPageRoute( // The slider will see the default ToggleButtonsTheme when built. builder: (BuildContext _) => toggleButtons, @@ -571,7 +571,7 @@ void main() { ElevatedButton( child: const Text('push wrapped'), onPressed: () { - Navigator.of(context)!.push( + Navigator.of(context).push( MaterialPageRoute( // Capture the shadow toggleButtons. builder: (BuildContext _) => InheritedTheme.captureAll(context, toggleButtons), @@ -603,7 +603,7 @@ void main() { expect(getTextColor('selected'), selectedButtonColor); expect(getTextColor('unselected'), buttonColor); - Navigator.of(navigatorContext)!.pop(); + Navigator.of(navigatorContext).pop(); await tester.pumpAndSettle(); // route animation await tester.tap(find.text('push unwrapped')); @@ -649,7 +649,7 @@ void main() { RaisedButton( child: const Text('push unwrapped'), onPressed: () { - Navigator.of(context)!.push( + Navigator.of(context).push( MaterialPageRoute( // The slider will see the default ButtonTheme when built. builder: (BuildContext _) => buttons, @@ -660,7 +660,7 @@ void main() { RaisedButton( child: const Text('push wrapped'), onPressed: () { - Navigator.of(context)!.push( + Navigator.of(context).push( MaterialPageRoute( // Capture the shadow toggleButtons. builder: (BuildContext _) => InheritedTheme.captureAll(context, buttons), @@ -695,7 +695,7 @@ void main() { expect(getButtonColor('disabled'), disabledButtonColor); expect(getButtonColor('enabled'), buttonColor); - Navigator.of(navigatorContext)!.pop(); + Navigator.of(navigatorContext).pop(); await tester.pumpAndSettle(); // route animation await tester.tap(find.text('push unwrapped')); diff --git a/packages/flutter/test/material/page_test.dart b/packages/flutter/test/material/page_test.dart index 588abf8c57..0bccee7305 100644 --- a/packages/flutter/test/material/page_test.dart +++ b/packages/flutter/test/material/page_test.dart @@ -282,7 +282,7 @@ void main() { '/': (BuildContext context) => Material( child: TextButton( child: const Text('PUSH'), - onPressed: () { Navigator.of(context)!.pushNamed('/b'); }, + onPressed: () { Navigator.of(context).pushNamed('/b'); }, ), ), '/b': (BuildContext context) => Container(child: const Text('HELLO')), @@ -737,7 +737,7 @@ void main() { expect(homeTapCount, 1); expect(pageTapCount, 0); - final ValueNotifier notifier = Navigator.of(homeScaffoldKey.currentContext!)!.userGestureInProgressNotifier; + final ValueNotifier notifier = Navigator.of(homeScaffoldKey.currentContext!).userGestureInProgressNotifier; expect(notifier.value, false); Navigator.push(homeScaffoldKey.currentContext!, MaterialPageRoute( diff --git a/packages/flutter/test/material/page_transitions_theme_test.dart b/packages/flutter/test/material/page_transitions_theme_test.dart index f31c98dfba..2db3f43e7c 100644 --- a/packages/flutter/test/material/page_transitions_theme_test.dart +++ b/packages/flutter/test/material/page_transitions_theme_test.dart @@ -26,7 +26,7 @@ void main() { '/': (BuildContext context) => Material( child: TextButton( child: const Text('push'), - onPressed: () { Navigator.of(context)!.pushNamed('/b'); }, + onPressed: () { Navigator.of(context).pushNamed('/b'); }, ), ), '/b': (BuildContext context) => const Text('page b'), @@ -52,7 +52,7 @@ void main() { '/': (BuildContext context) => Material( child: TextButton( child: const Text('push'), - onPressed: () { Navigator.of(context)!.pushNamed('/b'); }, + onPressed: () { Navigator.of(context).pushNamed('/b'); }, ), ), '/b': (BuildContext context) => const Text('page b'), @@ -85,7 +85,7 @@ void main() { '/': (BuildContext context) => Material( child: TextButton( child: const Text('push'), - onPressed: () { Navigator.of(context)!.pushNamed('/b'); }, + onPressed: () { Navigator.of(context).pushNamed('/b'); }, ), ), '/b': (BuildContext context) => const Text('page b'), @@ -125,7 +125,7 @@ void main() { '/': (BuildContext context) => Material( child: TextButton( child: const Text('push'), - onPressed: () { Navigator.of(context)!.pushNamed('/b'); }, + onPressed: () { Navigator.of(context).pushNamed('/b'); }, ), ), '/b': (BuildContext context) => const Text('page b'), @@ -169,7 +169,7 @@ void main() { '/': (BuildContext context) => Material( child: TextButton( child: const Text('push'), - onPressed: () { Navigator.of(context)!.pushNamed('/b'); }, + onPressed: () { Navigator.of(context).pushNamed('/b'); }, ), ), '/b': (BuildContext context) => StatefulBuilder( diff --git a/packages/flutter/test/material/popup_menu_test.dart b/packages/flutter/test/material/popup_menu_test.dart index 1d25e48281..b5b3173b35 100644 --- a/packages/flutter/test/material/popup_menu_test.dart +++ b/packages/flutter/test/material/popup_menu_test.dart @@ -124,7 +124,7 @@ void main() { await tester.tap(find.byKey(withCallbackKey)); await tester.pump(); await tester.pump(const Duration(seconds: 1)); - Navigator.of(popupContext)!.pop(); + Navigator.of(popupContext).pop(); await tester.pump(); expect(cancels, equals(2)); }); diff --git a/packages/flutter/test/material/range_slider_test.dart b/packages/flutter/test/material/range_slider_test.dart index 66c4e71186..285a20df2b 100644 --- a/packages/flutter/test/material/range_slider_test.dart +++ b/packages/flutter/test/material/range_slider_test.dart @@ -1372,12 +1372,12 @@ void main() { ElevatedButton( child: const Text('Next'), onPressed: () { - Navigator.of(context)!.pushReplacement( + Navigator.of(context).pushReplacement( MaterialPageRoute( builder: (BuildContext context) { return ElevatedButton( child: const Text('Inner page'), - onPressed: () { Navigator.of(context)!.pop(); }, + onPressed: () { Navigator.of(context).pop(); }, ); }, ), diff --git a/packages/flutter/test/material/slider_test.dart b/packages/flutter/test/material/slider_test.dart index 6fad7c4a54..3b85444da1 100644 --- a/packages/flutter/test/material/slider_test.dart +++ b/packages/flutter/test/material/slider_test.dart @@ -2086,12 +2086,12 @@ void main() { ElevatedButton( child: const Text('Next'), onPressed: () { - Navigator.of(context)!.pushReplacement( + Navigator.of(context).pushReplacement( MaterialPageRoute( builder: (BuildContext context) { return ElevatedButton( child: const Text('Inner page'), - onPressed: () { Navigator.of(context)!.pop(); }, + onPressed: () { Navigator.of(context).pop(); }, ); }, ), diff --git a/packages/flutter/test/material/snack_bar_test.dart b/packages/flutter/test/material/snack_bar_test.dart index 64812e12c5..8337fb524f 100644 --- a/packages/flutter/test/material/snack_bar_test.dart +++ b/packages/flutter/test/material/snack_bar_test.dart @@ -2035,7 +2035,7 @@ void main() { key: transitionTarget, child: const Text('PUSH'), onPressed: () { - Navigator.of(context)!.pushNamed('/second'); + Navigator.of(context).pushNamed('/second'); }, ), ), diff --git a/packages/flutter/test/material/text_field_focus_test.dart b/packages/flutter/test/material/text_field_focus_test.dart index cb454971f9..1fe547b169 100644 --- a/packages/flutter/test/material/text_field_focus_test.dart +++ b/packages/flutter/test/material/text_field_focus_test.dart @@ -38,7 +38,7 @@ void main() { expect(tester.testTextInput.isVisible, isFalse); - Navigator.of(tester.element(find.text('Dialog')))!.pop(); + Navigator.of(tester.element(find.text('Dialog'))).pop(); await tester.pump(); expect(focusNode.hasPrimaryFocus, isTrue); diff --git a/packages/flutter/test/material/will_pop_test.dart b/packages/flutter/test/material/will_pop_test.dart index 9ff3c725d3..54a21f419c 100644 --- a/packages/flutter/test/material/will_pop_test.dart +++ b/packages/flutter/test/material/will_pop_test.dart @@ -139,7 +139,7 @@ void main() { child: TextButton( child: const Text('X'), onPressed: () { - Navigator.of(context)!.push(MaterialPageRoute( + Navigator.of(context).push(MaterialPageRoute( builder: (BuildContext context) { return SampleForm( callback: () => Future.value(willPopValue), @@ -178,7 +178,7 @@ void main() { child: TextButton( child: const Text('X'), onPressed: () { - Navigator.of(context)!.push(MaterialPageRoute( + Navigator.of(context).push(MaterialPageRoute( builder: (BuildContext context) { return SampleForm( callback: () => Future.value(willPopValue), @@ -230,11 +230,11 @@ void main() { actions: [ TextButton( child: const Text('YES'), - onPressed: () { Navigator.of(context)!.pop(true); }, + onPressed: () { Navigator.of(context).pop(true); }, ), TextButton( child: const Text('NO'), - onPressed: () { Navigator.of(context)!.pop(false); }, + onPressed: () { Navigator.of(context).pop(false); }, ), ], ); @@ -252,7 +252,7 @@ void main() { child: TextButton( child: const Text('X'), onPressed: () { - Navigator.of(context)!.push(MaterialPageRoute( + Navigator.of(context).push(MaterialPageRoute( builder: (BuildContext context) { return SampleForm( callback: () => showYesNoAlert(context), @@ -338,7 +338,7 @@ void main() { child: TextButton( child: const Text('X'), onPressed: () { - Navigator.of(context)!.push(route); + Navigator.of(context).push(route); }, ), ); diff --git a/packages/flutter/test/widgets/focus_traversal_test.dart b/packages/flutter/test/widgets/focus_traversal_test.dart index 24a686fa87..c5545c441c 100644 --- a/packages/flutter/test/widgets/focus_traversal_test.dart +++ b/packages/flutter/test/widgets/focus_traversal_test.dart @@ -349,7 +349,7 @@ void main() { focusNode: testNode1, autofocus: true, onPressed: () { - Navigator.of(context)!.push( + Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return Center( @@ -358,7 +358,7 @@ void main() { focusNode: testNode2, autofocus: true, onPressed: () { - Navigator.of(context)!.pop(); + Navigator.of(context).pop(); }, child: const Text('Go Back'), ), @@ -1148,7 +1148,7 @@ void main() { focusNode: testNode1, autofocus: true, onPressed: () { - Navigator.of(context)!.push( + Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return Center( @@ -1159,7 +1159,7 @@ void main() { focusNode: testNode2, autofocus: true, onPressed: () { - Navigator.of(context)!.pop(); + Navigator.of(context).pop(); }, child: const Text('Go Back'), ), diff --git a/packages/flutter/test/widgets/inherited_theme_test.dart b/packages/flutter/test/widgets/inherited_theme_test.dart index 64dc318eaf..27ef1a78b4 100644 --- a/packages/flutter/test/widgets/inherited_theme_test.dart +++ b/packages/flutter/test/widgets/inherited_theme_test.dart @@ -59,7 +59,7 @@ void main() { behavior: HitTestBehavior.opaque, onTap: () { navigatorContext = context; - Navigator.of(context)!.push( + Navigator.of(context).push( TestRoute( useCaptureAll ? InheritedTheme.captureAll(context, const IconTextBox('Hello')) @@ -121,7 +121,7 @@ void main() { // Return to the home route useCaptureAll = true; - Navigator.of(navigatorContext)!.pop(); + Navigator.of(navigatorContext).pop(); await tester.pumpAndSettle(); // route transition // Verify that all is the same as it was when the test started diff --git a/packages/flutter/test/widgets/navigator_test.dart b/packages/flutter/test/widgets/navigator_test.dart index 1376508503..4c14361684 100644 --- a/packages/flutter/test/widgets/navigator_test.dart +++ b/packages/flutter/test/widgets/navigator_test.dart @@ -204,13 +204,13 @@ void main() { return ElevatedButton( child: const Text('Next'), onPressed: () { - Navigator.of(context)!.push( + Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return ElevatedButton( child: const Text('Inner page'), onPressed: () { - Navigator.of(context, rootNavigator: true)!.push( + Navigator.of(context, rootNavigator: true).push( MaterialPageRoute( builder: (BuildContext context) { return const Text('Dialog'); @@ -783,8 +783,8 @@ void main() { '/A/B': (BuildContext context) => OnTapPage( id: 'B', onTap: (){ - Navigator.of(context)!.popUntil((Route route) => route.isFirst); - Navigator.of(context)!.pushReplacementNamed('/C'); + Navigator.of(context).popUntil((Route route) => route.isFirst); + Navigator.of(context).pushReplacementNamed('/C'); }, ), '/C': (BuildContext context) => const OnTapPage(id: 'C', @@ -851,7 +851,7 @@ void main() { id: 'B', onTap: (){ // Pops all routes with bad predicate. - Navigator.of(context)!.popUntil((Route route) => false); + Navigator.of(context).popUntil((Route route) => false); }, ), }; @@ -929,7 +929,7 @@ void main() { '/A/B': (BuildContext context) => OnTapPage( id: 'B', onTap: () { - Navigator.of(context)!.pushNamedAndRemoveUntil('/D', ModalRoute.withName('/A')); + Navigator.of(context).pushNamedAndRemoveUntil('/D', ModalRoute.withName('/A')); }, ), '/D': (BuildContext context) => const Text('page D'), @@ -1597,7 +1597,7 @@ void main() { final Map routes = { '/' : (BuildContext context) => OnTapPage(id: '/', onTap: () { Navigator.pushNamed(context, '/A'); - Navigator.of(context)!.pop(); + Navigator.of(context).pop(); }), '/A': (BuildContext context) => OnTapPage(id: 'A', onTap: () { Navigator.pop(context); }), }; @@ -1825,12 +1825,12 @@ void main() { }); testWidgets('initial routes below opaque route are offstage', (WidgetTester tester) async { - final GlobalKey g = GlobalKey(); + final GlobalKey testKey = GlobalKey(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Navigator( - key: g, + key: testKey, initialRoute: '/a/b', onGenerateRoute: (RouteSettings s) { return MaterialPageRoute( @@ -1850,7 +1850,7 @@ void main() { expect(find.text('+/a+', skipOffstage: false), findsOneWidget); expect(find.text('+/a/b+'), findsOneWidget); - g.currentState!.pop(); + testKey.currentState!.pop(); await tester.pumpAndSettle(); expect(find.text('+/+'), findsNothing); @@ -1858,7 +1858,7 @@ void main() { expect(find.text('+/a+'), findsOneWidget); expect(find.text('+/a/b+'), findsNothing); - g.currentState!.pop(); + testKey.currentState!.pop(); await tester.pumpAndSettle(); expect(find.text('+/+'), findsOneWidget); @@ -1868,12 +1868,12 @@ void main() { testWidgets('Can provide custom onGenerateInitialRoutes', (WidgetTester tester) async { bool onGenerateInitialRoutesCalled = false; - final GlobalKey g = GlobalKey(); + final GlobalKey testKey = GlobalKey(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Navigator( - key: g, + key: testKey, initialRoute: 'Hello World', onGenerateInitialRoutes: (NavigatorState navigator, String initialRoute) { onGenerateInitialRoutesCalled = true; @@ -1893,7 +1893,7 @@ void main() { expect(find.text('Hello'), findsNothing); expect(find.text('World'), findsOneWidget); - g.currentState!.pop(); + testKey.currentState!.pop(); await tester.pumpAndSettle(); expect(find.text('Hello'), findsOneWidget); @@ -1901,16 +1901,16 @@ void main() { }); testWidgets('Navigator.of able to handle input context is a navigator context', (WidgetTester tester) async { - final GlobalKey g = GlobalKey(); + final GlobalKey testKey = GlobalKey(); await tester.pumpWidget( MaterialApp( - navigatorKey: g, + navigatorKey: testKey, home: const Text('home'), ) ); - final NavigatorState state = Navigator.of(g.currentContext!)!; - expect(state, g.currentState); + final NavigatorState state = Navigator.of(testKey.currentContext!); + expect(state, testKey.currentState); }); testWidgets('Navigator.of able to handle input context is a navigator context - root navigator', (WidgetTester tester) async { @@ -1931,7 +1931,61 @@ void main() { ) ); - final NavigatorState state = Navigator.of(sub.currentContext!, rootNavigator: true)!; + final NavigatorState state = Navigator.of(sub.currentContext!, rootNavigator: true); + expect(state, root.currentState); + }); + + testWidgets('Navigator.maybeOf throws when there is no navigator', (WidgetTester tester) async { + final GlobalKey testKey = GlobalKey(); + await tester.pumpWidget(SizedBox(key: testKey)); + + expect(() async { + Navigator.of(testKey.currentContext!); + }, throwsFlutterError); + }); + + testWidgets('Navigator.maybeOf works when there is no navigator', (WidgetTester tester) async { + final GlobalKey testKey = GlobalKey(); + await tester.pumpWidget(SizedBox(key: testKey)); + + final NavigatorState? state = Navigator.maybeOf(testKey.currentContext!); + expect(state, isNull); + }); + + testWidgets('Navigator.maybeOf able to handle input context is a navigator context', (WidgetTester tester) async { + final GlobalKey testKey = GlobalKey(); + await tester.pumpWidget( + MaterialApp( + navigatorKey: testKey, + home: const Text('home'), + ) + ); + + final NavigatorState? state = Navigator.maybeOf(testKey.currentContext!); + expect(state, isNotNull); + expect(state, testKey.currentState); + }); + + testWidgets('Navigator.maybeOf able to handle input context is a navigator context - root navigator', (WidgetTester tester) async { + final GlobalKey root = GlobalKey(); + final GlobalKey sub = GlobalKey(); + await tester.pumpWidget( + MaterialApp( + navigatorKey: root, + home: Navigator( + key: sub, + onGenerateRoute: (RouteSettings settings) { + return MaterialPageRoute( + settings: settings, + builder: (BuildContext context) => const Text('dummy'), + ); + }, + ), + ) + ); + + final NavigatorState? state = Navigator.maybeOf(sub.currentContext!, rootNavigator: true); + expect(state, isNotNull); expect(state, root.currentState); }); diff --git a/packages/flutter/test/widgets/page_route_builder_test.dart b/packages/flutter/test/widgets/page_route_builder_test.dart index d7c7fd5010..c69d9afb90 100644 --- a/packages/flutter/test/widgets/page_route_builder_test.dart +++ b/packages/flutter/test/widgets/page_route_builder_test.dart @@ -26,7 +26,7 @@ class HomePage extends StatefulWidget { class _HomePageState extends State { void _presentModalPage() { - Navigator.of(context)!.push(PageRouteBuilder( + Navigator.of(context).push(PageRouteBuilder( transitionDuration: const Duration(milliseconds: 300), barrierColor: Colors.black54, opaque: false, @@ -62,7 +62,7 @@ class ModalPage extends StatelessWidget { highlightColor: Colors.transparent, splashColor: Colors.transparent, onTap: () { - Navigator.of(context)!.pop(); + Navigator.of(context).pop(); }, child: const SizedBox.expand(), ), diff --git a/packages/flutter/test/widgets/routes_test.dart b/packages/flutter/test/widgets/routes_test.dart index 967f0ee608..e279969e24 100644 --- a/packages/flutter/test/widgets/routes_test.dart +++ b/packages/flutter/test/widgets/routes_test.dart @@ -563,7 +563,7 @@ void main() { builder: (BuildContext context) { return ElevatedButton( onPressed: () { - Navigator.of(context)!.push( + Navigator.of(context).push( PageRouteBuilder( settings: settings, pageBuilder: (BuildContext context, Animation input, Animation out) { @@ -612,7 +612,7 @@ void main() { builder: (BuildContext context) { return ElevatedButton( onPressed: () { - Navigator.of(context)!.push( + Navigator.of(context).push( PageRouteBuilder( settings: settings, pageBuilder: (BuildContext context, Animation input, Animation out) { @@ -1138,7 +1138,7 @@ void main() { builder: (BuildContext context) { return ElevatedButton( onPressed: () { - Navigator.of(context)!.push( + Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext innerContext) { return Container( @@ -1188,7 +1188,7 @@ void main() { builder: (BuildContext context) { return ElevatedButton( onPressed: () { - Navigator.of(context)!.push( + Navigator.of(context).push( ModifiedReverseTransitionDurationRoute( builder: (BuildContext innerContext) { return Container( @@ -1247,7 +1247,7 @@ void main() { builder: (BuildContext context) { return ElevatedButton( onPressed: () { - Navigator.of(context)!.push( + Navigator.of(context).push( ModifiedReverseTransitionDurationRoute( builder: (BuildContext innerContext) { return Container( @@ -1309,7 +1309,7 @@ void main() { child: ElevatedButton( child: const Text('X'), onPressed: () { - Navigator.of(context)!.push( + Navigator.of(context).push( _TestDialogRouteWithCustomBarrierCurve( child: const Text('Hello World'), ) @@ -1371,7 +1371,7 @@ void main() { child: ElevatedButton( child: const Text('X'), onPressed: () { - Navigator.of(context)!.push( + Navigator.of(context).push( _TestDialogRouteWithCustomBarrierCurve( child: const Text('Hello World'), barrierCurve: Curves.linear, @@ -1436,7 +1436,7 @@ void main() { child: ElevatedButton( child: const Text('X'), onPressed: () { - Navigator.of(context)!.push( + Navigator.of(context).push( _TestDialogRouteWithCustomBarrierCurve( child: const Text('Hello World'), barrierLabel: 'test label',