我想实现制作一个上面有不同项目的抽屉,所以我正在为DrawerItems
创建一个单独的文件,并使用构造函数,将数据传递给主文件。但是我在onP的
函数上得到以下错误:
"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,
);
}
}
有人知道为什么吗?
更改您的代码以接受VoidCallback
而不是函数
。
顺便说一句,VoidCallback
只是void Function()
的简写,因此您也可以将其定义为最终的void Function()onP的;
更新代码:
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,
);
}
}
而不是
final Function? onPressed; // Bad
使用
final void Function()? onPressed; // Good
final VoidCallback? onPressed; // Good
好吧,那是因为FlatButton
中的onP的
不是它的VoidCallBack
函数的普通函数。你可以尝试这样的东西:
final VoidCallBack onPressed;
同时,您将普通的函数
传递给VoidCallBack
按照这里的官方文档
更新代码:
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,
);
}
}