繁体   English   中英

在 Flutter 中的容器中添加 5 次点击事件

[英]Add 5 time tap event to container in Flutter

我想向容器添加 5 次点击事件。 我正在使用 GestureDetector 来获取点击事件。 但我不知道如何在其中实现 5 次点击事件。 我想当用户在容器上点击 5 次时,我想在我的应用程序中执行一些操作。

我通过以下方式实现了

GestureDetector(
  child: Image.asset(
    ImageLogo,
    width: MediaQuery.of(context).size.width * 0.30,
    fit: BoxFit.fitWidth,
  ),
  onTap: () {
    tapCounter = 0;
    oldTimestamp = 0;
  },
  onDoubleTap: () {
    int currentTimestamp = DateTime.now().millisecondsSinceEpoch;
    print('currentTimestamp $currentTimestamp');
    print('oldTimestamp $oldTimestamp');
    print('tapCounter $tapCounter');
    if (tapCounter == 0) {
      oldTimestamp = 0;
    }
    if (oldTimestamp == 0 ||
        currentTimestamp - oldTimestamp < 450) {
      tapCounter += 2;
      oldTimestamp = currentTimestamp;
      if (tapCounter == 6) {
        tapCounter = 0;
        oldTimestamp = 0;
        print('Do some operation');
      }
    } else {
      tapCounter = 0;
    }
  },
)

我正在存储当前时间并比较旧时间和当前时间,这是因为当用户停止点击容器时,它会将计数器重置为 0。

您可以轻松地使用一块 state 来实现这一点,在下面的示例中,如果_counter == 5 ,我使用了一个Opacity小部件来显示一个图标,这可能不是您想要的,但根据您的问题的上下文,这就是我能给。

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  int _counter = 0;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => setState(() => _counter++),
      child: Container(
          child: Column(
        children: <Widget>[
          Text('Tap me'),
          Opacity(
            opacity: _counter == 5 ? 1 : 0,
            child: Icon(
              Icons.whatshot
            ),
          )
        ],
      )),
    );
  }
}

暂无
暂无

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

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