I want to achieve to make a drawer with different items on it, so I am creating a separate file for the DrawerItems
and the with the constructor, pass the data to the main file. But I get the following error on the onPressed
function:
"The argument type 'Function' can't be assigned to the parameter type 'void Function()'"
class DrawerItem extends StatelessWidget {
final String text;
final Function onPressed;
const DrawerItem({Key key, this.text, this.onPressed}) : super(key: key);
@override
Widget build(BuildContext context) {
return FlatButton(
child: Text(
text,
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: 18.0,
),
),
onPressed: onPressed,
);
}
}
Anyone knows why?
Change your code to accept a VoidCallback
instead of Function
for the onPressed
.
By the way VoidCallback
is just shorthand for void Function()
so you could also define it as final void Function() onPressed;
Updated code:
class DrawerItem extends StatelessWidget {
final String text;
final VoidCallback onPressed;
const DrawerItem({Key key, this.text, this.onPressed}) : super(key: key);
@override
Widget build(BuildContext context) {
return FlatButton(
child: Text(
text,
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: 18.0,
),
),
onPressed: onPressed,
);
}
}
Instead of
final Function? onPressed; // Bad
use
final void Function()? onPressed; // Good
final VoidCallback? onPressed; // Good
Well that's because onPressed
inside FlatButton
is not a normal function its VoidCallBack
Function.
You can try something like this:
final VoidCallBack onPressed;
While, you are passing a normal function
into a VoidCallBack
Follow the official doc here
Updated Code:
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomeScreen(),
);
}
}
class HomeScreen extends StatelessWidget {
_myFunction() => print("Being pressed!");
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
DrawerItem(
text: "Hello Jee",
onPressed: _myFunction,
),
],
),
),
);
}
}
class DrawerItem extends StatelessWidget {
final String text;
final Function onPressed;
const DrawerItem({Key key, this.text, this.onPressed}) : super(key: key);
@override
Widget build(BuildContext context) {
return FlatButton(
child: Text(
text,
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: 18.0,
),
),
onPressed: onPressed,
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With