如何在Flutter小部件上模拟点击事件

如何在Flutter小部件上模拟点击事件

本文介绍了如何在Flutter小部件上模拟点击事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何模拟Flutter小部件上的点击事件?

How can I simulate tap event on a Flutter widget?

例如,如何模拟对Tabbar标题的点击?更重要的是,我如何首先找到小部件?请注意,我不想调用相关的回调,也不想使用Flutter测试类测试窗口小部件,但我想模拟运行时在窗口小部件上的轻敲。

For example, how do I simulate tapping on a Tabbar title? And more importantly, how can I find the widget in the first place? Please note that I don't want to call the relevant callbacks, nor testing widgets using Flutter test classes, but I'd like to simulate the tapping on widgets at runtime instead.

编辑1 :(请注意)
我不想测试小部件或调用分配给GestureDetector.onTap或RaisedButton.onPressed等的方法...

EDIT 1: (Please Note)I DO NOT want to test a widget or call a method that is assigned to a GestureDetector.onTap or RaisedButton.onPressed etc...

推荐答案

首先,获取 RenderBox 。然后只需调用 hitTest 方法。只要安装在树上,任何人都可以。

First, obtain a RenderBox. Then just call hitTest method. Any will do, as long as it's mounted in the tree.

为此,您必须使用 BuildContext 通过 context.findRenderObject()

To do so you'll have to use BuildContext through context.findRenderObject().

BuildContext context;

final renderObj = context.findRenderObject();
if (renderObj is RenderBox) {
  final hitTestResult = HitTestResult();
  if (renderObj.hitTest(hitTestResult, position:  /* The offset where you want to "tap" */)) {
    // a descendant of `renderObj` got tapped
    print(hitTestResult.path);
  }
}

这篇关于如何在Flutter小部件上模拟点击事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 12:10