The argument type 'Function' can't be assigned to the parameter type 'void Function()?' after null safety
Change your code to accept a VoidCallback instead of Function for the onPressed.Btw 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, ); } }
With null safety:
Instead of
final Function? onPressed;
use
final VoidCallback? onPressed;
or
final Function()? onPressed;
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, ); }}