mirror of
https://github.com/flutter/flutter.git
synced 2026-02-20 02:29:02 +08:00
Merge pull request #1603 from yjbanov/no-navigator-message
better error message when Navigator is used with no NavigatorState in…
This commit is contained in:
commit
aa1017e067
@ -157,6 +157,11 @@ class Navigator extends StatefulComponent {
|
||||
|
||||
static void openTransaction(BuildContext context, NavigatorTransactionCallback callback) {
|
||||
NavigatorState navigator = context.ancestorStateOfType(const TypeMatcher<NavigatorState>());
|
||||
assert(() {
|
||||
if (navigator == null)
|
||||
throw new WidgetError('openTransaction called with a context that does not include a Navigator. The context passed to the Navigator.openTransaction() method must be that of a widget that is a descendant of a Navigator widget.');
|
||||
return true;
|
||||
});
|
||||
navigator.openTransaction(callback);
|
||||
}
|
||||
|
||||
|
||||
@ -40,6 +40,29 @@ class SecondComponentState extends State<SecondComponent> {
|
||||
}
|
||||
}
|
||||
|
||||
typedef void ExceptionCallback(exception);
|
||||
|
||||
class ThirdComponent extends StatelessComponent {
|
||||
ThirdComponent({ this.targetKey, this.onException });
|
||||
|
||||
final Key targetKey;
|
||||
final ExceptionCallback onException;
|
||||
|
||||
Widget build(BuildContext context) {
|
||||
return new GestureDetector(
|
||||
key: targetKey,
|
||||
onTap: () {
|
||||
try {
|
||||
Navigator.openTransaction(context, (_) { });
|
||||
} catch (e) {
|
||||
onException(e);
|
||||
}
|
||||
},
|
||||
behavior: HitTestBehavior.opaque
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
test('Can navigator navigate to and from a stateful component', () {
|
||||
testWidgets((WidgetTester tester) {
|
||||
@ -73,4 +96,21 @@ void main() {
|
||||
expect(tester.findText('Y'), isNull);
|
||||
});
|
||||
});
|
||||
|
||||
test('Navigator.openTransaction fails gracefully when not found in context', () {
|
||||
testWidgets((WidgetTester tester) {
|
||||
Key targetKey = new Key('foo');
|
||||
dynamic exception;
|
||||
Widget widget = new ThirdComponent(
|
||||
targetKey: targetKey,
|
||||
onException: (e) {
|
||||
exception = e;
|
||||
}
|
||||
);
|
||||
tester.pumpWidget(widget);
|
||||
tester.tap(tester.findElementByKey(targetKey));
|
||||
expect(exception, new isInstanceOf<WidgetError>());
|
||||
expect('$exception', startsWith('openTransaction called with a context'));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user