Unverified Commit 345188d4 authored by chunhtai's avatar chunhtai Committed by GitHub

make Router.of nullable (#67683)

parent 08576cb6
......@@ -302,10 +302,19 @@ class Router<T> extends StatefulWidget {
/// router to create a [ChildBackButtonDispatcher] for a nested router.
/// Another use case may be updating the value in [routeInformationProvider]
/// to navigate to a new route.
static Router<dynamic> of(BuildContext context) {
final _RouterScope scope = context.dependOnInheritedWidgetOfExactType<_RouterScope>()!;
assert(scope != null);
return scope.routerState.widget;
static Router<dynamic>? of(BuildContext context, {bool nullOk = false}) {
final _RouterScope? scope = context.dependOnInheritedWidgetOfExactType<_RouterScope>();
assert(() {
if (scope == null && !nullOk) {
throw FlutterError(
'Router operation requested with a context that does not include a Router.\n'
'The context used to retrieve the Router must be that of a widget that '
'is a descendant of a Router widget.'
);
}
return true;
}());
return scope?.routerState.widget;
}
/// Forces the [Router] to run the [callback] and reports the route
......
......@@ -79,6 +79,28 @@ void main() {
});
});
testWidgets('Router.of can be null', (WidgetTester tester) async {
final GlobalKey key = GlobalKey();
await tester.pumpWidget(buildBoilerPlate(
Text('dummy', key: key)
));
final BuildContext textContext = key.currentContext;
// This should not throw error.
Router<dynamic> router = Router.of(textContext, nullOk: true);
expect(router, isNull);
// Test when the nullOk is not specified.
bool hasFlutterError = false;
try {
router = Router.of(textContext);
} on FlutterError catch(e) {
expect(e.message.startsWith('Router'), isTrue);
hasFlutterError = true;
}
expect(hasFlutterError, isTrue);
});
testWidgets('Simple router can handle pop route', (WidgetTester tester) async {
final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider();
provider.value = const RouteInformation(
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment