gpt4 book ai didi

flutter - 如何在 flutter 中实现超时按钮

转载 作者:行者123 更新时间:2023-12-04 01:07:39 25 4
gpt4 key购买 nike

用户可以点击按钮直到计时器结束。我不知道如何开始布局。 flutter sdk 是否有针对这种情况的任何内置(或类似的待实现)小部件。

enter image description here

最佳答案

您可以使用 CustomPainter 小部件轻松实现它。检查下面的源代码并根据您的需要进行调整。

enter image description here


import 'dart:async';

import 'package:flutter/material.dart';

class MyProgressButton extends StatefulWidget {
@override
_MyProgressButtonState createState() => _MyProgressButtonState();
}

class _MyProgressButtonState extends State<MyProgressButton> {
Timer _timer;
int _progress = 0;
int _totalActionTimeInSeconds = 3;

void _initCounter() {
_timer?.cancel();
_progress = 0;
_timer = Timer.periodic(const Duration(milliseconds: 50), (_) {
setState(() => _progress += 50);

if (Duration(milliseconds: _progress).inSeconds >= _totalActionTimeInSeconds) {
_timer.cancel();
// Do something
}
});
}

void _stopCounter() {
_timer?.cancel();
setState(() => _progress = 0);
}

@override
Widget build(BuildContext context) {
return GestureDetector(
onTapDown: (_) => _initCounter(),
onTapUp: (_) => _stopCounter(),
child: CustomPaint(
painter: _MyCustomButtonPainter((_progress / 1000) / _totalActionTimeInSeconds),
child: Container(
alignment: Alignment.center,
width: 500.0,
height: 200.0,
child: Text('Press me'),
),
),
);
}
}

class _MyCustomButtonPainter extends CustomPainter {
const _MyCustomButtonPainter(this.progress);

final double progress;

@override
void paint(Canvas canvas, Size size) {
final Paint paint = Paint()..color = Colors.grey;
final double buttonWidth = size.width;
final double buttonHeight = size.height;

canvas.drawRRect(
RRect.fromRectAndRadius(
Rect.fromLTRB(0.0, 0.0, buttonWidth, buttonHeight),
Radius.circular(5.0),
),
paint,
);

paint.color = Colors.green;

canvas.drawRRect(
RRect.fromRectAndRadius(
Rect.fromLTRB(0.0, 0.0, progress * buttonWidth, buttonHeight),
Radius.circular(5.0),
),
paint,
);
}

@override
bool shouldRepaint(_MyCustomButtonPainter oldDelegate) => this.progress != oldDelegate.progress;
}

关于flutter - 如何在 flutter 中实现超时按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65902029/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com