flutter - Flutter:如何将带参数的函数传递给子类
问题描述
如何将带参数的函数传递给 Flutter 中的子类?
我当前的代码如下所示。
parent.dart
class _ParentState extends State<Parent> {
int _currentIndex = 0;
Widget callPage(int currentIndex) {
switch (currentIndex) {
case 0:
return Child(
aFunction: _aFunction('hello')
);
case 1:
return Child1();
case 2:
return Child2();
default:
return Child();
}
}
@override
Widget build(Buildcontext context) {
...
}
Future<void> _aFunction(String arg) async {
...
}
}
child.dart
class Child extends StatefulWidget {
final Function(String hello) aFunction;
Child({this.aFunction});
}
...
class _ChildState extends State<Child> {
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.symmetric(horizontal: 12.0),
child: RefreshIndicator(
onRefresh: widget.aFunction, // How can I refer to the argument here?
我不知道该怎么做,但无论如何我都尝试过这种方式,并且 Parent 类中有错误。它说
参数类型 Future 不能分配给参数类型“动态函数(字符串)”
解决方案
只需传递函数的引用,如下所示。您不必添加字符串参数_aFunction("hello")。
Widget callPage(int currentIndex) {
switch (currentIndex) {
case 0:
return Child(
aFunction: _aFunction
);
case 1:
return Child1();
case 2:
return Child2();
default:
return Child();
}
}
然后您可以从子小部件中调用该函数
RefreshIndicator(child: Container(), onRefresh: widget.aFunction("Hello")
推荐阅读
- wordpress - 如何在mac上安装wp cli
- c++ - 以不同的比特率去交织音频数据
- python - 如何获得今天和上一个日期之间的天数差异?
- amazon-web-services - Lambda 角色没有在 SAM 模板中定义的策略
- sql-server - 多个复合索引与单个非聚集列存储索引
- google-sheets - 我可以在谷歌表格的 IFS 函数中使用二元运算符 OR 和 AND 吗?
- python-3.x - 为什么我得到一个意外的关键字参数“calculate_hit_box”
- python - 类问题 - 程序按预期工作,但 Visual Studio 代码突出显示语法错误
- python - 无法使用python脚本保存excel文件
- python - 如何在 SentenceTransformers 中设置代理?