diff --git a/packages/flutter/lib/src/cupertino/nav_bar.dart b/packages/flutter/lib/src/cupertino/nav_bar.dart index e6d84441bd..d7394ab251 100644 --- a/packages/flutter/lib/src/cupertino/nav_bar.dart +++ b/packages/flutter/lib/src/cupertino/nav_bar.dart @@ -1231,7 +1231,7 @@ class CupertinoNavigationBarBackButton extends StatelessWidget { Widget build(BuildContext context) { final ModalRoute currentRoute = ModalRoute.of(context); assert( - currentRoute.canPop, + currentRoute?.canPop == true, 'CupertinoNavigationBarBackButton should only be used in routes that can be popped', ); diff --git a/packages/flutter/test/cupertino/nav_bar_test.dart b/packages/flutter/test/cupertino/nav_bar_test.dart index 4493f78021..09419a0393 100644 --- a/packages/flutter/test/cupertino/nav_bar_test.dart +++ b/packages/flutter/test/cupertino/nav_bar_test.dart @@ -883,6 +883,28 @@ void main() { ); expect(SystemChrome.latestStyle, SystemUiOverlayStyle.dark); }); + + testWidgets('CupertinoNavigationBarBackButton shows an error when manually added outside a route', (WidgetTester tester) async { + await tester.pumpWidget( + const CupertinoNavigationBarBackButton() + ); + + final dynamic exception = tester.takeException(); + expect(exception, isAssertionError); + expect(exception.toString(), contains('CupertinoNavigationBarBackButton should only be used in routes that can be popped')); + }); + + testWidgets('CupertinoNavigationBarBackButton shows an error when placed in a route that cannot be popped', (WidgetTester tester) async { + await tester.pumpWidget( + const CupertinoApp( + home: CupertinoNavigationBarBackButton(), + ), + ); + + final dynamic exception = tester.takeException(); + expect(exception, isAssertionError); + expect(exception.toString(), contains('CupertinoNavigationBarBackButton should only be used in routes that can be popped')); + }); } class _ExpectStyles extends StatelessWidget {