gpt4 book ai didi

animation - Flutter Widget 测试等待动画

转载 作者:行者123 更新时间:2023-12-04 15:04:34 25 4
gpt4 key购买 nike

我有一个类似于以下的小部件测试:

testWidgets('Widget test', (WidgetTester tester) async {
provideMockedNetworkImages(() async {
final widget = MyWidget();

await WidgetTestFunctions.pumpWidgetTest(
tester,
widget,
);

// ....

await tester.tap(find.byType(MyWidget));
await tester.pump(new Duration(milliseconds: 3000));

// ....

expect(widget.value, myValue);
});
});
以及小部件的 on-tap 方法的以下实现:
_onButtonPressed() async {      
await animationController.forward();
setState(() {
// ...
// Calls method that changes the widget value.
});
}
我遇到的问题是在调用 animationController.forward() 之后方法在测试 setState部分不执行。我应该如何等待此方法正确完成?在应用程序运行时,这部分代码被正确调用。
好像 await tester.pump(new Duration(milliseconds: 3000));工作不正常,动画的持续时间为 1500 毫秒,如您所见,泵持续时间是两倍。

最佳答案

我遇到了同样的问题,这就是正在发生的事情。
当你做

await animationController.forward();
您不是在等待一个简单的 Future<void>完成,但 TickerFuture (扩展 Future<void>)。
出于某种原因,在我的测试中,有些 TickerFuture来自 animationController.forward()被取消了。
TickerProvider 的文档中, 它说:

If the Ticker is disposed without being stopped, or if it is stopped with canceled set to true, then this Future will never complete.


This class works like a normal Future, but has an additional property, orCancel, which returns a derivative Future that completes with an error if the Ticker that returned the TickerFuture was stopped with canceled set to true, or if it was disposed without being stopped.


To run a callback when either this future resolves or when the ticker is canceled, use whenCompleteOrCancel.


现在,问题与 whenCompleteOrCancel是它返回 void (而不是 Future<void> 所以我们等不及了。
所以这就是我所做的(受 whenCompleteOrCancel 的实现启发):
Future<void> thunk(dynamic value) {
return;
}
final TickerFuture ticker = animationController.forward();
await ticker.onCancel.then(thunk, onError: thunk); // <- This resolves even if the ticker is canceled and the tests are not stuck anymore.

关于animation - Flutter Widget 测试等待动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66402424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com