简体   繁体   English

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

[英]How can I simulate a tap event on a Flutter widget?

How can I simulate tap event on a Flutter widget?如何在 Flutter 小部件上模拟点击事件?

For example, how do I simulate tapping on a Tabbar title?例如,如何模拟点击 Tabbar 标题? 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.请注意,我不想调用相关的回调,也不想使用 Flutter 测试类测试小部件,但我想在运行时模拟对小部件的点击。

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

First, obtain a RenderBox . 首先,获取RenderBox Then just call hitTest method. 然后只需调用hitTest方法。 Any will do, as long as it's mounted in the tree. 任何人都会这样做,只要它安装在树上。

To do so you'll have to use BuildContext through context.findRenderObject() . 为此,您必须通过context.findRenderObject()使用BuildContext

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);
  }
}

如果小部件具有定义的 onTap 属性,只需调用

widget.onTap();

Use GestureBinding to simulate a click event anywhere on the screen:使用GestureBinding模拟屏幕任意位置的点击事件:

演示 gif

Full example:完整示例:

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Column(
          children: [
            ElevatedButton(
              onPressed: () {},
              style: ElevatedButton.styleFrom(
                primary: Colors.red[900],
              ),
              child: SizedBox(
                width: 400,
                height: 400,
                child: Center(child: Text("I'm a big button.")),
              ),
            ),
            ElevatedButton(
              onPressed: () async {
                GestureBinding.instance!.handlePointerEvent(PointerDownEvent(
                  position: Offset(200, 300),
                ));
                await Future.delayed(Duration(milliseconds: 500));
                GestureBinding.instance!.handlePointerEvent(PointerUpEvent(
                  position: Offset(200, 300),
                ));
              },
              child: Text('Simulate Click'),
            ),
          ],
        ),
      ),
    );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM