make Router.of nullable (#67683)
This commit is contained in:
parent
08576cb671
commit
345188d40e
@ -302,10 +302,19 @@ class Router<T> extends StatefulWidget {
|
|||||||
/// router to create a [ChildBackButtonDispatcher] for a nested router.
|
/// router to create a [ChildBackButtonDispatcher] for a nested router.
|
||||||
/// Another use case may be updating the value in [routeInformationProvider]
|
/// Another use case may be updating the value in [routeInformationProvider]
|
||||||
/// to navigate to a new route.
|
/// to navigate to a new route.
|
||||||
static Router<dynamic> of(BuildContext context) {
|
static Router<dynamic>? of(BuildContext context, {bool nullOk = false}) {
|
||||||
final _RouterScope scope = context.dependOnInheritedWidgetOfExactType<_RouterScope>()!;
|
final _RouterScope? scope = context.dependOnInheritedWidgetOfExactType<_RouterScope>();
|
||||||
assert(scope != null);
|
assert(() {
|
||||||
return scope.routerState.widget;
|
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
|
/// 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 {
|
testWidgets('Simple router can handle pop route', (WidgetTester tester) async {
|
||||||
final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider();
|
final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider();
|
||||||
provider.value = const RouteInformation(
|
provider.value = const RouteInformation(
|
||||||
|
Loading…
x
Reference in New Issue
Block a user