按钮图片
我已经定义了一个 RoundIconButton 来增加用户点击按钮时的计数。
如果用户需要将计数增加 50,则必须点击 50 次。
当用户点击并按住时,如何更改按钮以连续增加计数?
int age = 20;
RoundIconButton(
icon: FontAwesomeIcons.plus,
onPressed: () {
setState(() {
age++;
});
class RoundIconButton extends StatelessWidget {
RoundIconButton({@required this.icon, @required this.onPressed});
final IconData icon;
final Function onPressed;
@override
Widget build(BuildContext context) {
return RawMaterialButton(
child: Icon(icon),
onPressed: onPressed,
elevation:
6.0, // will show only when onpress is defined. it is disabled by default.
shape: CircleBorder(),
fillColor: Color(0xFF4C4F5E),
constraints: BoxConstraints.tightFor(
width: 56.0,
height: 56.0,
),
);
}
}
最佳答案
为了实现您的目标,您需要使用 Timer
的组合来自 dart:async
包装与 GestureDetector
.以下是基于您提供的示例图像的完整示例。
class WeightSelect extends StatefulWidget {
@override
_WeightSelectState createState() => _WeightSelectState();
}
class _WeightSelectState extends State<WeightSelect> {
Timer _timer;
var _weight = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
padding: const EdgeInsets.all(16.0),
decoration: BoxDecoration(
color: Colors.grey.shade600,
borderRadius: BorderRadius.circular(20.0)
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text("Weight".toUpperCase(),style: TextStyle(
fontSize: 24.0,
fontWeight: FontWeight.w500,
color: Colors.indigo,
),),
const SizedBox(height: 10.0),
Text("$_weight",style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 30.0,
),),
const SizedBox(height: 10.0),
Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
GestureDetector(
child: Container(
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.blue,
),
width: 60,
height: 60,
child: Center(
child: Container(
color: Colors.white,
width: 20,
height: 5.0,
),
),
),
onTap: (){
setState(() {
if(_weight > 0 ) _weight--;
});
},
onTapDown: (TapDownDetails details) {
print('down');
_timer = Timer.periodic(Duration(milliseconds: 100), (t) {
setState(() {
if(_weight > 0 )
_weight--;
});
print('value $_weight');
});
},
onTapUp: (TapUpDetails details) {
print('up');
_timer.cancel();
},
onTapCancel: () {
print('cancel');
_timer.cancel();
},
),
const SizedBox(width: 10.0),
GestureDetector(
child: Container(
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.blue,
),
width: 60,
height: 60,
child: Center(
child: Icon(Icons.add,size: 40.0, color: Colors.white,),
),
),
onTap: (){
setState(() {
_weight++;
});
},
onTapDown: (TapDownDetails details) {
print('down');
_timer = Timer.periodic(Duration(milliseconds: 100), (t) {
setState(() {
_weight++;
});
print('value $_weight');
});
},
onTapUp: (TapUpDetails details) {
print('up');
_timer.cancel();
},
onTapCancel: () {
print('cancel');
_timer.cancel();
},
),
],
),
],
),
),
),
);
}
}
关于flutter - 如何对按钮进行编程以在点击并按住时连续增加或减少计数器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59552545/