'Flutter: Passing a function as parameter to a Stateful Widget Class
I have a stateful widget that returns a scaffold as follows:
class TimerPage extends StatefulWidget {
const TimerPage({Key? key, required this.title}) : super(key: key);
final String title;
@override
TimerPageState createState() => TimerPageState();
}
class TimerPageState extends State<TimerPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
mainAxisAlignment: MainAxisAlignment.center,
children: [
getMaterialTextButton('1', 'Roboto', 24, keypadPressed('1')), /// ERROR
getMaterialTextButton('2', 'Roboto', 24, keypadPressed2('2')), /// ERROR
]
),
);
}
}
So what I'm trying to do is pass a generic function inside getMaterialTextButton() that will return a material button as follows:
// this function is within the TimerPageState class
Widget getMaterialTextButton(String text, String fontname, double fontsize, Function onPressAction) {
return (
MaterialButton(
onPressed: () {
onPressAction(text);
},
color: Colors.blue,
textColor: Colors.white,
child: Text(
text,
style: TextStyle(fontFamily: fontname, fontSize: fontsize)
),
padding: const EdgeInsets.all(24),
shape: const CircleBorder(),
)
);
}
// this function is to be called when the button 1 is pressed
// also resides inside TimerPageState class
void keyPressed (String text) {
print('Pressed: $text');
}
// this function is also to be called when button 2 is pressed
// also resides inside TimerPageState class
void keyPressed2 (String text) {
print('Pressed: $text');
}
But this doesn't seem to work as dart is giving me an exception:
Exception has occurred. _TypeError (type 'Null' is not a subtype of type 'Function')
. How can I do this operation properly?
Solution 1:[1]
you are passing the return value of the function, not the function itself
change this
getMaterialTextButton('1', 'Roboto', 24, keypadPressed('1')),
to this
getMaterialTextButton('1', 'Roboto', 24, keypadPressed),
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | omar hatem |
