animation - Flutter Widget 测试等待动画

标签 animation widget widget-test-flutter

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

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/

相关文章:

ios - UITableView 在 reloadData 时消失了

android - 向上滑动动画覆盖 fragment 而不是同时动画两个 fragment

css - Blogspots 小部件 CSS 位置 : fixed; and Chrome 的奇怪问题

python - 从 Django 的 TextArea 小部件中删除标签

flutter - 如何在 Flutter 测试中找到 `FlatButton.icon`?

c++ - 如何平滑地移动 Sprite ?

android - 如何获取附加到动画的 View ?

python - 小部件中的 tkinter 默认按钮

flutter - Codemagic:如何设置集成测试 Android 模拟器

InkWell tap 的 Flutter 小部件测试失败