如何 return 来自 VoidCallback 函数的值
How to return value from VoidCallback function
我有一个带有按钮的自定义小部件。我想创建 VoidCallback 派系以从中获取 return 数据。
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,
// 原始 class
CustomCalender(onDayChanged: (){print("HI");}),
我正在使用这个 flutter 包
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),
),
);
}
}
我有一个带有按钮的自定义小部件。我想创建 VoidCallback 派系以从中获取 return 数据。
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,
// 原始 class
CustomCalender(onDayChanged: (){print("HI");}),
我正在使用这个 flutter 包
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),
),
);
}
}