类型"Null"不是函数类型的子类型

  • 本文关键字:类型 函数 Null flutter
  • 更新时间 :
  • 英文 :


我想将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);
},
),
],
),
);
}
}

最新更新