如何获得一个按钮更新计数器只有一次时按第一次?



我有两个容器按钮(蓝色和红色),当按下时交替可见。加上一个计数器,每次按下蓝色按钮,它就会滴答作响。

class Test extends StatefulWidget {
const Test({Key? key}) : super(key: key);
@override
State<Test> createState() => _TestState();
}
class _TestState extends State<Test> {
int counter = 0;
bool blueVisibility = true;
bool redVisibility = false;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Expanded(
child: Row(
children: [
Expanded(
child: Container(
child: Visibility(
visible: blueVisibility,
child: InkWell(
onTap: () {
setState(() {
redVisibility = true;
blueVisibility = false;
counter++;
});
},
child: Container(
margin: EdgeInsets.all(10),
color: Colors.blue,
height: 80,
width: 50,
),
),
),
),
),
Expanded(
child: Container(
child: Visibility(
visible: redVisibility,
child: InkWell(
onTap: () {
setState(() {
redVisibility = false;
blueVisibility = true;
});
},
child: Container(
margin: EdgeInsets.all(10),
color: Colors.red,
height: 80,
width: 50,
),
),
),
),
),
],
),
),
Container(
height: 50,
width: 50,
color: Colors.blueGrey,
alignment: Alignment.center,
child: Text(
'$counter',
style: TextStyle(
fontSize: 40,
),
),
),
],
),
);
}
}

是否有可能使蓝色盒子只在第一次按下时添加到计数器中,然后在此之后不再添加,同时仍然保留按下盒子以使它们可见/不可见的能力?

thanks so much

您可以用if else语句包装代码,以实现您想要的效果,如下所示。在蓝色容器按钮的onTap中:

onTap: () {
setState(() {
redVisibility = true;
blueVisibility = false;
if(counter < 1) {
counter++;
}
});
},

这将使计数器只增加一次。

int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
int counter = 0;
bool blueVisibility = true;
bool redVisibility = false;
int check=0;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Expanded(
child: Row(
children: [
Expanded(
child: Container(
child: Visibility(
visible: blueVisibility,
child: InkWell(
onTap: () {
setState(() {
redVisibility = true;
blueVisibility = false;
if(check==0){
counter++;
check++;}
});
},
child: Container(
margin: EdgeInsets.all(10),
color: Colors.blue,
height: 80,
width: 50,
),
),
),
),
),
Expanded(
child: Container(
child: Visibility(
visible: redVisibility,
child: InkWell(
onTap: () {
setState(() {
redVisibility = false;
blueVisibility = true;
});
},
child: Container(
margin: EdgeInsets.all(10),
color: Colors.red,
height: 80,
width: 50,
),
),
),
),
),
],
),
),
Container(
height: 50,
width: 50,
color: Colors.blueGrey,
alignment: Alignment.center,
child: Text(
'$counter',
style: TextStyle(
fontSize: 40,
),
),
),
],
),
);}
}

相关内容

最新更新