`import 'package:flutter/material.dart';
class SkillEntry extends StatefulWidget {
const SkillEntry({super.key, required this.skll});
final String skll;
@override
State<SkillEntry> createState() => _SkillEntryState();
}
class _SkillEntryState extends State<SkillEntry> {
@override
Widget build(BuildContext context) {
int skillvalue = 0;
return Container(
height: 40,
width: 200,
child: Row(children: [
const Flexible(flex: 20, child:
TextField(decoration:(
InputDecoration(
border: OutlineInputBorder(),
hintText: ('Name and Skill'))),)),
ElevatedButton(onPressed: PlusOne(skillvalue), child: Icon(Icons.add_circle)),
ElevatedButton(onPressed: MinusOne(skillvalue), child: Icon(Icons.exposure_minus_1)),
Flexible(flex: 7, child:
Text('$skillvalue',)),
]));
}
PlusOne(skillvalue) {
setState(() {
skillvalue = skillvalue + 1;
return skillvalue;
});
}
MinusOne(skillvalue) {
setState(() {
skillvalue = skillvalue - 1;
return skillvalue;
});
}
}
As it stands currently the buttons seemingly do nothing. I suspect that I’m getting the skillvalue
variable into the function PlusOne
but not properly returning it to the main program, or I might not be using setstate
correctly. How can I solve this?
2
Answers
The problem is that your
skillValue
is declared within your build method:And the
build
method re-runs everysetState
. SoskillValue
will be reset to the value you set it every time you update the UI.To solve the problem, move the
skillValue
in theState
class:instead of the
build
methodfirst of all,
skillValue
is declared inbuild
method, the value will always be zero.secondly, the way you use
ElevatedButton
is wrong, you can not use a void method return value as a parameter toonPressed
, which means theonPressed
always be null.here is my demo code.