简体   繁体   English

Flutter/Dart:从 Switch/Case 返回值

[英]Flutter/Dart: Returning value from Switch/Case

I am trying to build a date validator in my flutter application, using a switch case:我正在尝试使用 switch 案例在我的颤振应用程序中构建一个日期验证器:

Link to DartPad sample链接到 DartPad 示例

class DateValidator {
  DateValidator({this.selectedDate, this.type});
  final String type;
  final DateTime selectedDate;


  dateValidator() {
    String _errorMsg = '';
    switch (type) {
      case "event":
        {
          if (selectedDate == null) _errorMsg = "No date selected";
          if (selectedDate == DateTime.now())
            _errorMsg = "Check your selected date";
        }
        break;

      case "test2":
        {
          print("test2");
        }
        break;

      default:
        {
          print("Invalid Date");
        }
        break;
    }

    return _errorMsg;
  }
}

void main() {
  DateValidator(
    selectedDate: DateTime.now(),
    type: 'event',
  ).dateValidator().then((value) {
    print(value);
  });
}

I would like to then return _errorMsg like so:我想然后像这样返回 _errorMsg :

DateValidator(type: widget.deal.date).dateValidator()
.then((errorMsg){
  print(errorMsg);
});

This results in:这导致:

Class 'bool' has no instance method 'then'. 'bool' 类没有实例方法 'then'。

How can I correctly return the value?如何正确返回值?

Replace your:更换您的:

dateValidator() {

With:和:

Future<String> dateValidator() async {

Reason to do this: If you want to get your result in then method then you need to specify your method's return type as Future<String> because then is a method defined in Future class.这样做的原因:如果你想在then方法中得到你的结果, then你需要将你的方法的返回类型指定为Future<String>因为then是一个在Future类中定义的方法。

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

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