我想将2提供给函数。当函数接收到2作为数据时,它应该将成功打印到控制台。但是会抛出一个错误。
错误:type 'Null' is not a subtype of type Function
~~~PAGE1 for button
const ToolSetButton(
{Key? key,
this.function = myRunFunction,
const Function myRunFunction = defaultFunction;
void defaultFunction() {
print('Button Tapped');
}
第2页,上面的小部件正在使用
enum ButtonList {One, Two, Three}
调用函数
function: testFunc(ButtonList.Two)),
testFunc( ButtonList type) {
if (type == ButtonList.Two ){print('sucess ')};
}
~~~PAGE 3正在执行函数
在inkwell内部执行函数
class ToolSetButton extends StatefulWidget {
final Function function ;
}
child: InkWell(
splashColor: Colors.white,
onTap: () {
Function.apply(widget.function, [], {});
},
如果我正确地得到它,你想当你点击ToolSetButton
时,如果它的类型是ButtonList.two
,你想要成功打印在控制台上。一种简单的方法是将ToolSetButton
小部件更改为具有buttonType
参数(编辑:您还可以传递自己的函数):
enum ButtonList { One, Two, Three }
class ToolSetButton extends StatefulWidget {
const ToolSetButton({
required this.buttonType,
required this.buttonText,
required this.myFunction,
Key? key,
}) : super(key: key);
final ButtonList buttonType;
final String buttonText;
final Function myFunction;
@override
_ToolSetButtonState createState() => _ToolSetButtonState();
}
class _ToolSetButtonState extends State<ToolSetButton> {
@override
Widget build(BuildContext context) {
return InkWell(
onTap: () {
widget.myFunction();
},
child: Text(widget.buttonText),
);
}
}
现在当你使用createToolSetButton
时,你可以定义它的类型供以后使用,也可以传递你自己的函数在onTap
:
class TestClass extends StatelessWidget {
const TestClass({Key? key}) : super(key: key);
void testFunc(ButtonList type) {
if (type == ButtonList.Two) {
print('sucess ');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ToolSetButton(
buttonText: 'One',
buttonType: ButtonList.One,
myFunction: () {
testFunc(ButtonList.One);
},
),
ToolSetButton(
buttonText: 'Two',
buttonType: ButtonList.Two,
myFunction: () {
testFunc(ButtonList.Two);
},
),
ToolSetButton(
buttonText: 'Three',
buttonType: ButtonList.Three,
myFunction: () {
testFunc(ButtonList.Three);
},
),
],
),
);
}
}