在我的州级课程中,我宣布了一个未来:
Future<void> _testFuture;
并像这样分配它initState
:
super.initState();
_testFuture = Future(() async {
await Future.value(1); //can be any computation
});
并FutureBuilder
像这样使用它:
FutureBuilder(
future: _testFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done)
return Text('Hi');
else
return Center(
child: CircularProgressIndicator(),
);
},
),
这在正常运行应用程序时工作正常,flutter run
但是当我尝试使用小部件测试它时flutter test test/widget_test.dart
:
void main() {
testWidgets('Testing', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.runAsync(() async {
await tester.pumpWidget(MyApp());
await tester.pumpAndSettle();
});
}
它失败了:
══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following assertion was thrown while running async test code:
pumpAndSettle timed out
但是,如果我以这种方式分配未来,则相同的测试将毫无问题地通过:
super.initState();
Future<void> testFutures() async {
await Future.value(1);
}
_testFuture = testFutures();
两种分配未来的方式有什么区别?