有没有办法在没有用户交互的情况下触发 onLongPress?

时间:2021-01-26 06:57:32

标签: flutter flutter-layout flutter-dependencies

    GestureDetector(
      onLongPress: (){    
        print("LONG PRESS");
       },
    child:Text("......")),  

Now I want to trigger onLongPress without any user interaction. 

请给出您宝贵的答复。

1 个答案:

答案 0 :(得分:1)

以下是您如何触发任何 Gesture 的方法,无论是 onTaponLongPress 还是任何其他。

 GestureDetector gestureDetector = GestureDetector(
    onLongPress: () {
      print('Long Press Called');
    },
    child: Text('Long Press'),
  );

  @override
  Widget build(BuildContext context) {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      gestureDetector.onLongPress();
    });
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Gesture'),
      ),
      body: Center(
        child: gestureDetector,
      ),
    );
  }

输出:

I/flutter (19590): Long Press Called

在这段代码中,我在 onLongPress 上调用 addPostFrameCallback,它将在小部件加载后调用。您可以随时调用 gestureDetector.onLongPress(),无需用户交互即可触发 onLongPress