我有个问题我想禁用按钮3秒,如果用户点击它。3秒后,用户应该能够再次单击按钮。我创建了一个变量_hasBeenPressed
。但问题是我的输出并不是我所希望的。什么都没发生。如果我点击按钮,按钮的颜色不会改变。
那么,如果按下按钮并在此期间禁用onTap,我如何在3秒钟内更改按钮的颜色?
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../utils/definitions.dart';
import 'icons.dart';
import '../model/label.dart';
class LabelButton extends StatefulWidget {
final Label? label;
final VoidStringCallback? process;
LabelButton({required this.label, required this.process, Key? key})
: super(key: key);
@override
State<LabelButton> createState() => _LabelButtonState();
const LabelButton._(this.label, this.process, {Key? key})
: super(key: key);
static LabelButton createBlank() {
return const LabelButton._(null, null);
}
}
class _LabelButtonState extends State<LabelButton> {
bool _hasBeenPressed = false;
@override
Widget build(BuildContext context) {
if (widget.label != null) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: ClipRRect(
borderRadius: BorderRadius.circular(12),
child: Material(
child: InkWell(
highlightColor: Color(0xFF00D3F8).withOpacity(0.3),
splashColor: Color(0xFFB20DD3).withOpacity(0.3),
onTap: () {
setState(() async {
/*Timer(Duration(seconds: 3), (){
_hasBeenPressed = !_hasBeenPressed;
print("inside" + _hasBeenPressed.toString()); //prints true
});
_hasBeenPressed = !_hasBeenPressed;
print(_hasBeenPressed); // prints false
*/
_hasBeenPressed = true;
print("CLICKED");
await Future.delayed(const Duration(seconds: 3), () {
print("nach");
_hasBeenPressed = false;
});
print(_hasBeenPressed);
});
widget.process!(widget.label!.identifier, widget.label!.category, widget.label!.id);
HapticFeedback.lightImpact();
},
child: Ink(
width: 100, // Breite anpassen
height: 120, // Höhe anpassen
//padding: const EdgeInsets.all(10.0),
decoration: BoxDecoration(
color: _hasBeenPressed ? const Color(0xFFB6B6B6) : Colors.green
/*border: Border.all(
color: Colors.black, // Rahmenfarbe anpassen
width: 2, // Rahmendicke anpassen
),*/
//borderRadius: BorderRadius.circular(12), // Eckradius anpassen
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(iconList
.firstWhere((element) => element.name == widget.label!.uiIcon)
.icon,
size: 80,),
/*const Icon(CustomIcons.construction,
size: 80,),*/
Text(widget.label!.categoryName,
style: const TextStyle(
color: Color(0xFF696969),
//fontWeight: FontWeight.bold,
)),
Text(widget.label!.name,
style: const TextStyle(
fontWeight: FontWeight.bold,
)), // Text unter dem Icon
],
),
),
),
)
)
);
}
else {
return Container();
}
}
}
2条答案
按热度按时间3lxsmp7m1#
您正在等待几秒钟,然后才发射
setState((){});
。这就是问题的根源。egdjgwm82#
我不知道你想干什么。
但是你需要纠正一些事情,例如,
setState(() async {
setState不能异步完成。你可以做如下。如果你想的话