简体   繁体   English

Flutter Widget 在自定义回调中返回值

[英]Flutter Widget return value in a custom callback

I've created my own Widget which consists in a DatePicker , here the code:我创建了自己的Widget ,它包含在DatePicker ,这里是代码:

class DatePicker extends StatelessWidget {
  final Icon icon;
  final DateTime initialDate;
  final ValueChanged<DateTime> onDateSelected;

  DatePicker({this.icon = const Icon(Icons.date_range), @required this.initialDate, this.onDateSelected});

  Future<Null> _selectDate(BuildContext context) async {
    final DateTime picked = await showDatePicker(context: context, initialDate: initialDate, firstDate: DateTime(2015, 8), lastDate: DateTime(2101));
    if (picked != null && picked != initialDate) {
      // TODO: return the picked value in the 'OnDateSelect' callback
      print(picked.toString());
    }
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: <Widget>[
        Text(initialDate.toString()),
        IconButton(
          icon: this.icon,
          onPressed: () => _selectDate(context),
        )
      ],
    );
  }
}

I want to use it like this:我想像这样使用它:

DatePicker(
      initialDate: _ticketDate,
      onDateSelected: (newDate) {
        print(newDate);
      },
    );

What I don't know is how to return the date selected in my custom onDateSelected callback once the Future<Null> _selectDate has been executed.我不知道的是如何在Future<Null> _selectDate执行后返回在我的自定义onDateSelected回调中选择的日期。

Any ideas?有任何想法吗?

It's very simple:这很简单:

All you do is call the function provided by the widget and provide the parameter, in this case, the picked date.您所做的就是调用小部件提供的函数并提供参数,在本例中为所选日期。

  Future<void> _selectDate(BuildContext context) async {
    final DateTime picked = await showDatePicker(
        context: context,
        initialDate: initialDate,
        firstDate: DateTime(2015, 8),
        lastDate: DateTime(2101));
    if (picked != null && picked != initialDate) {
      onDateSelected(picked); // just do this
    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM