【发布时间】:2022-11-01 18:36:14
【问题描述】:
我创建了 3 个计数器。前两个有一个加号和减号按钮,使按钮中间的计数器上升和下降到最大值 8。它们都影响最后一个计数器(全局计数器),最大值为 12。
我遇到的问题是,当 globalCounter 达到 12 时,我如何停止任一添加按钮的工作?例如如果 counterOne 为 7,我如何让 counterTwo 在达到 5 时关闭(全局计数器为 12)
here is my code:
void main() {
runApp(
const MyApp(),
);
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: Scaffold(
backgroundColor: Colors.black,
body: SafeArea(child: ButtonProblem()),
),
);
}
}
class ButtonProblem extends StatefulWidget {
const ButtonProblem({Key? key}) : super(key: key);
@override
State<ButtonProblem> createState() => _ButtonProblemState();
}
class _ButtonProblemState extends State<ButtonProblem> {
int counterOne = 0;
int counterTwo = 0;
int globalCounter = 0;
@override
Widget build(BuildContext context) {
return Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ClipRRect(
borderRadius: BorderRadius.circular(5.0),
child: InkWell(
onTap: () {
setState(() {
if (counterOne > 0) counterOne--;
if (globalCounter > 0) globalCounter--;
});
},
child: Container(
child: Icon(Icons.remove, color: Colors.white),
width: 25.0,
height: 35.0,
color: Colors.blueGrey[900],
),
),
),
Container(
child: Text(
'$counterOne',
style: TextStyle(
fontFamily: 'SourceSansPro',
fontSize: 40.0,
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
),
ClipRRect(
borderRadius: BorderRadius.circular(5.0),
child: InkWell(
onTap: () {
setState(() {
if (counterOne < 8) counterOne++;
if (globalCounter < 12) globalCounter++;
});
},
child: Container(
child: Icon(Icons.add, color: Colors.white),
width: 25.0,
height: 35.0,
color: Colors.blueGrey[900],
),
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ClipRRect(
borderRadius: BorderRadius.circular(5.0),
child: InkWell(
onTap: () {
setState(() {
if (counterTwo > 0) counterTwo--;
if (globalCounter > 0) globalCounter--;
});
},
child: Container(
child: Icon(Icons.remove, color: Colors.white),
width: 25.0,
height: 35.0,
color: Colors.blueGrey[900],
),
),
),
Container(
child: Text(
'$counterTwo',
style: TextStyle(
fontFamily: 'SourceSansPro',
fontSize: 40.0,
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
),
ClipRRect(
borderRadius: BorderRadius.circular(5.0),
child: InkWell(
onTap: () {
setState(() {
if (counterTwo < 8) counterTwo++;
if (globalCounter < 12) globalCounter++;
});
},
child: Container(
child: Icon(Icons.add, color: Colors.white),
width: 25.0,
height: 35.0,
color: Colors.blueGrey[900],
),
),
),
],
),
Container(
child: Center(
child: Text(
'$globalCounter/12',
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'SourceSansPro',
fontSize: 35.0,
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
),
),
],
);
}
}
【问题讨论】: