I am making an app and am now getting this error. I don’t know why. I’ve tried looking at every other StackOverflow post about this error, and I tried all the suggestions, but nothing worked. Here is the code:
class ParentWidgetState extends State<ParentWidget> {
int counter = 0;
List scrambles = ["F R U R' U' F'", 'F U R B D', 'D B2 U2 S'];
void incrementCounter() {
setState(() {
counter++;
});
}
bool active = false;
void _handleTapboxChanged(bool newValue) {
setState(() {
active = newValue;
});
}
@override
Widget build(BuildContext context) {
return SizedBox(
child: TapboxB(
active: active,
onChanged: _handleTapboxChanged,
scrambles: scrambles,
counter: counter,
incrementCounter: incrementCounter(), **This is where the error occurs**
),
);
}
}
And here you can see I made this ‘incrementCounter’ method required for TapBoxB. The reason why I made this ‘incrementCounter’ required was so that I could call the method inside the onPressed(){} of the TextButton(). Any help is appreciated.
class TapboxB extends StatelessWidget {
final bool active;
final ValueChanged<bool> onChanged;
final List scrambles;
final int counter;
final int incrementCounter;
const TapboxB({
super.key,
this.active = false,
required this.incrementCounter,
required this.onChanged,
required this.scrambles,
required this.counter,
});
void _handleTap() {
onChanged(!active);
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: _handleTap,
child: Container(
width: 200,
height: 200,
decoration: const BoxDecoration(color: null),
child: Center(
child: TextButton(
onPressed: () {
incrementCounter;
},
child: Text('${scrambles[counter % scrambles.length]}'),
),
// child: Text('Ignore this)
// ),
),
),
);
}
}
If anyone can provide an answer and explain how they fixed the error, that’d be great.
3
Answers
The problems is within your code:
You are calling the function using parenthesis
()
,instead you should just pass a reference to it.Also, in your code, you are accepting it as an
int
but it should really be afunction
.Instead of:
Use:
While it is just about getting tap event, I will suggest using
VoidCallback
.And use like
method
incrementCounter()
doesn’t return a value as evidenced by the keywordvoid
:in the same time
TapboxB(...)
expectincrementCounter
that isint
.that’s why you got an error:
‘This expression has a type of ‘void’ so its value can’t be used’.
you should pas
int
:or you should use
void Function()
orVoidCallback
in the Tabbox: