使用Future .then(_)和" return"用Dart语言

时间:2014-10-15 21:07:21

标签: dart future

我有一个自定义元素,其中一个函数在返回元素之前从服务器调用SQL语句。问题是:执行SQL需要很长时间,因此函数返回NULL元素,稍后再完成SQL。

初始代码是:

  Element launchElement(){
        getItems();
        return(innerDiv);
    }

但是由于这个问题,我尝试使用Future来控制它

  Element launchElement(){
     Future fonixFuture() => new Future.value(true);
     fonixFuture()
            .then((_)=> getItems())
            .then((_)=> return(innerDiv));
 }

但在Dart编辑器中列出了很长的错误列表,如下所示:

Multiple markers at this line
- Expected to find 
 ';'
- Expected to find 
 ';'
- Expected to find 
 ';'
- Dead code
- Unexpected 
 token ')'
- Expected an 
 identifier
- Expected an 
 identifier
- Expected to find 
 ')'

get item函数是对服务器的简单调用,用于从SQL获取输出:

 getItems(){  
    request = new HttpRequest();
    request.onReadyStateChange.listen(onData_getItems);

    request.open('POST', host+'/getItems');
    request.send(' ');  
  }

  onData_getItems(_){
    if (request.readyState == HttpRequest.DONE && request.status == 200) {   

     for(Map item in JSON.decode(request.responseText)){
         LineItem..children.add(new OptionElement(value: item['Code'], data: item['Name']));
    }         
} 
else if (request.readyState == HttpRequest.DONE &&
  request.status == 0) { 
     fonixFooter.classes..add('serverERROR');
     fonixFooter.innerHtml= "could not connect to server, contact your admin";  
}
else
  { 
     fonixFooter.classes..add('serverERROR');
     fonixFooter.innerHtml= "Failed to fetch data from server, contact your admin";  
  }

}

自定义元素本身是:

class purchaseLines extends HtmlElement {
    static final tag = 'purchase-lines';
    factory purchaseLines() => new Element.tag(tag);

    var innerDiv, LineItem;

    purchaseLines.created() : super.created() {      
        innerDiv = new cardFonix().launchElement();

        LineItem = new SelectElement()
              ..children.add(new OptionElement(value: '0', data:'Stock Code'));

         var LineQty = new InputElement()
                  ..type='number'
                   ..placeholder='Qty'  ;   

        LineQty.onKeyUp.listen((e){if(LineQty.checkValidity() == false)LineQty.value='0';});
        var Lineprice = new InputElement()
             ..type='number'
             ..placeholder='price';

          Lineprice.onKeyUp.listen((e){if(Lineprice.checkValidity() == false)Lineprice.value='0';});
          innerDiv.nodes..add(LineItem)..add(LineQty)..add(Lineprice); 
    }

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

这不是合法的语法:

.then((_) => return(innerDiv));

在Dart中,return不是函数。我想也许你只想要这个:

.then((_) => innerDiv);

你的函数调用应该是这样的:

Future<Element> launchElement(){
  return new Future.value(true)
        .then((_) => getItems())
        .then((_) => innerDiv);
}