我有一个定义如下的小部件:
import ...;
...
class TechnicalError extends StatelessWidget {
...
@override
Widget build(BuildContext context) {
TechnicalErrorPayload payload = ModalRoute.of(context).settings.arguments;
return Scaffold(
body: Column(...)
);
}
}
我还为该小部件定义了一个命名路由:
import ...;
const String TECHNICAL_DIFFICULTIES = '/technical-difficulties';
class MyApp extends StatelessWidget {
MyApp() {
...
}
@override
Widget build(BuildContext context) {
return MaterialApp(
routes: <String, WidgetBuilder> {
...
TECHNICAL_DIFFICULTIES: (BuildContext context) => TechnicalError()
}
...
);
}
}
每当我想推那条路线时,我都会做如下操作:
var techErrPayload = TechnicalErrorPayload(...);
await Navigator.of(context).pushNamed(TECHNICAL_DIFFICULTIES, arguments: techErrPayload);
一切正常。问题出在我要测试TechnicalError小部件时...如何将TechnicalErrorPayload传递给该小部件?它不是构造函数的一部分。它由ModalRoute的属性获取。
这行不通:
testWidgets('Me testing', (WidgetTester tester) async {
MaterialPageRoute test = MaterialPageRoute(
builder: (BuildContext context) => TechnicalError(),
settings: RouteSettings(
name: 'Blah',
arguments: TechnicalErrorPayload(friendlyErrorMessage: 'Hey Joe')
)
);
//await tester.pumpWidget(WidgetWrapper.fromRouteWithNavigatorObservers(test, [navigatorobserverMock]));
await tester.pumpWidget(
MaterialApp(
navigatorObservers: [navigatorobserverMock],
routes: {
'/': (BuildContext context) => test.builder(context)
},
)
);
await tester.pumpAndSettle();
});
答案 0 :(得分:0)
为了测试使用路由参数的路由,我将屏幕小部件 a 包裹在一个 材料页面路由。然后在路由设置中,我可以传递路由所需的任何参数。
await tester.pumpWidget(
MaterialApp(
onGenerateRoute: (settings) {
return MaterialPageRoute(
settings: RouteSettings(arguments: // Your Argument here),
builder: (context) {
return TheScreen();
},
);
},
)
);