flutter - 如何从 VoidCallback 函数返回值
问题描述
我有一个带有按钮的自定义小部件。我想创建 VoidCallback 派系以从中返回数据。
onDayPressed: (DateTime date, List<Event> events){
// I want to return date time to original class when the user changes the date
}
我尝试这样做但不起作用
onDayPressed: (DateTime date, List<Event> events) => widget.onDayChanged,
// 在原始类上
CustomCalender(onDayChanged: (){print("HI");}),
我正在使用这个颤振包
flutter_calendar_carousel
解决方案
如果您需要将数据从子节点传递给父节点,则必须使用 Function(T),因为 VoidCallback 不支持传递数据。请参见下面的代码示例:
// Try adapting this code to work with your code, the principle should be the same.
class MinimalExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
// Notice the variable being passed in the function.
body: ReturnValueToParent( myNumber: (int) => print(int),),
);
}
}
// Specify a Function(DateTime) in your case and adapt it to your problem.
class ReturnValueToParent extends StatelessWidget {
final Function(int) myNumber;
const ReturnValueToParent({Key key, this.myNumber}) : super(key: key);
@override
Widget build(BuildContext context) {
return Center(
child: RaisedButton(
// Remember the parameter
onPressed: () => myNumber(5),
),
);
}
}
推荐阅读
- java - Spring mongo 存储库 crud 结合标准
- python - 如何删除 /r 并解决我在使用 BeautifulSoup 时遇到的奇怪的格式问题?
- python - 为什么我不能在 pycharm 编辑器中导入 pyperclip?
- android - IllegalStateException:reasonPhrase 在 Android WebView 中不能为空
- graalvm - 捆绑的 Graal VM 与其他 VM + Graal JIT 的区别
- json - file_get_contents 解析 json 插入数据库
- css - VSCode - 自动创建匹配的 CSS 文件
- python - 模拟返回模拟对象而不是返回值
- excel - 访问另一个库中工作簿的数据
- javascript - JS RegExp 在第二次出现时开始