简体   繁体   English

我想将 function 添加到 FloatingActionButton

[英]I want to add function to the FloatingActionButton

I want the FloatingActionButton to hold a Timer and change color five seconds after tapping it.我希望 FloatingActionButton 在点击它五秒钟后保持一个计时器并改变颜色。 I tried using the Timer that the parent Widget has, but then the entire screen refresh.我尝试使用父 Widget 具有的 Timer,但随后整个屏幕刷新。 So I thought I could separate the FloatingActionButton as a single StatefulWidget and add function to it, but I don't know how to do that?所以我想我可以将 FloatingActionButton 分离为单个 StatefulWidget 并添加 function ,但我不知道该怎么做? Is it possible to use something called "extends"?是否可以使用称为“扩展”的东西? 〜〜〜 〜〜〜

I took your advice and created a NewClass, It's pretty good.我听取了您的建议并创建了一个 NewClass,它非常好。 but I would like to set _counter=0 every time I tap it.但我想在每次点击它时设置 _counter=0 。

class CustomFloatingButton extends StatefulWidget {
  final VoidCallback onTap;
  CustomFloatingButton({required this.onTap});

  @override
  State<CustomFloatingButton> createState() => _CustomFloatingButtonState();
}

class _CustomFloatingButtonState extends State<CustomFloatingButton> {
  int _counter = 0;
  late Timer timer;

  dynamic buttonColor() {
    if (_counter < 6) {
      return Colors.grey;
    } else {
      return Colors.teal;
      } 
    }
  }

  @override
  void initState() {
    super.initState();
    timer = Timer.periodic(
      const Duration(seconds: 1),
      (Timer timer) {
        _counter++;
        if (_counter > widget.quizLimit) {
          timer.cancel();
        }
        setState(() {});
        print(_counter);
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: widget.onTap,
      child: Container(
        height: 50,
        width: 50,
        decoration: BoxDecoration(
          color: buttonColor(),
          borderRadius: BorderRadius.circular(28),
        ),
        alignment: Alignment.center,
        child: const Icon(
          Icons.arrow_forward,
          color: Colors.white,
        ),
      ),
    );
  }
}
NewFloatingActionButton(
  backgroundColor:getButtonColor(),
   onPressed(){
     setState(() {
       counter=0;
     });
   })

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

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