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

时间:2019-12-09 23:48:20

标签: flutter dart callback widget

我创建了自己的.custom-select_drop_flight { position: relative; font-family: Arial; } .custom-select_drop_flight select { display: none; } .select-selected { background-color: DodgerBlue; } .select-selected:after { position: absolute; content: ""; top: 14px; right: 10px; width: 0; height: 0; border: 6px solid transparent; border-color: #fff transparent transparent transparent; } ,其中包含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),
        )
      ],
    );
  }
}

执行DatePicker( initialDate: _ticketDate, onDateSelected: (newDate) { print(newDate); }, ); onDateSelected后,我不知道如何返回在自定义Future<Null>回调中选择的日期。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

这很简单:

您要做的就是调用窗口小部件提供的函数并提供参数(在这种情况下为选择的日期)。

  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
    }
  }