Flutter Execute方法,只要按下按钮 [英] Flutter Execute Method so long the button pressed

查看:148
本文介绍了Flutter Execute方法,只要按下按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户按下按钮时,我需要执行方法,换句话说,在此按操作期间,用户将按下按钮不明的时间段.在此时间段内,我需要执行方法,任何人都知道我该如何做在Flutter中做到了这一点,我尝试了GestureDetector,但是没有这样做的选择,而且onLongPress也没有此选项,因为在按下Operation之后触发的Long Press上,我将为我需要的内容编写psudo代码:

I need to Execute Method when the user press buton and during this Pressing Operation in other words the user will press the button for unkown period of time ai need to execute method during this Period of time any one have an idea how i can do that in Flutter i tried GestureDetector but there are no Option to do that also onLongPress hasn't this option becouse on Long Press triggered after the press Operation I will write psudo code for what i need:

While(Button.isPressed){
 //Execute Method
 }

推荐答案

使用Listener和有状态的小部件.在每个循环之后,我还引入了一些延迟:

Use a Listener and a stateful widget. I also introduced a slight delay after every loop:

import 'dart:async';

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(brightness: Brightness.dark),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  bool _buttonPressed = false;
  bool _loopActive = false;

  void _increaseCounterWhilePressed() async {
    // make sure that only one loop is active
    if (_loopActive) return;

    _loopActive = true;

    while (_buttonPressed) {
      // do your thing
      setState(() {
        _counter++;
      });

      // wait a bit
      await Future.delayed(Duration(milliseconds: 200));
    }

    _loopActive = false;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Center(
        child: Listener(
          onPointerDown: (details) {
            _buttonPressed = true;
            _increaseCounterWhilePressed();
          },
          onPointerUp: (details) {
            _buttonPressed = false;
          },
          child: Container(
            decoration: BoxDecoration(color: Colors.orange, border: Border.all()),
            padding: EdgeInsets.all(16.0),
            child: Text('Value: $_counter'),
          ),
        ),
      ),
    );
  }
}

这篇关于Flutter Execute方法,只要按下按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆