2014-05-14 55 views
1

下面的葉子小號空文件中讀取後退出:保存在DART範圍的對象以外的範圍

String s; 
new File('etc.stk').readAsString().then((String contents) { 
    s = contents; 
}); 
// s is null here. 

有沒有辦法保存(或克隆)S,還是我不得不只用它在那麼範圍內?

我有幾千行的解析和運行文件內容的編譯器/解釋器代碼,並且不希望它們都在新的File範圍內。

編輯

爲了提供更多的背景,我試圖做的是一樣的東西

new File('etc1.stk').readAsString() 
    .then((String script) {  
     syntaxTree1 = buildTree(script); 
    }); 
new File('etc2.stk').readAsString() 
    .then((String script) { 
     syntaxTree2 = buildTree(script); 
    }); 

,並有機會獲得這兩個syntaxTree1和syntaxTree2在隨後的代碼。如果可以的話,我會繞過飛鏢道。

回答

3

EDIT
(該代碼測試)

import 'dart:async' as async; 
import 'dart:io' as io; 

void main(args) { 
// approach1: inline 
    async.Future.wait([ 
    new io.File('file1.txt').readAsString(), 
    new io.File('file2.txt').readAsString() 
    ]).then((values) { 
    values.forEach(print); 
    }); 

// approach2: load files in another function 
    getFiles().then((values) { 
    values.forEach(print); 
    }); 
} 

async.Future<List> getFiles() { 
    return async.Future.wait([ 
    new io.File('file1.txt').readAsString(), 
    new io.File('file2.txt').readAsString() 
    ]); 
} 

輸出:

file1的
file2的

file1的
文件2

編輯結束

暗示:

// s is null here 

是因爲執行該行中的代碼沒有測試之前

s = contents 

此代碼

new File('etc.stk').readAsString() 

返回在事件隊列中入伍並在執行的實際「線程」完成時執行的未來。

如果您提供了更多的代碼,我會爲建議的解決方案提供更好的上下文。
你可以做什麼是

String s; 
new File('etc.stk').readAsString().then((String contents) { 
    s = contents; 
}).then((_) { 
// s is **NOT** null here. 
}); 

//String s; 
new File('etc.stk').readAsString().then((String contents) { 
    //s = contents; 
    someCallback(s) 
}); 
// s is null here. 

void someCallback(String s) { 
    // s is **NOT** null here 
} 

Future<String> myReadAsString() { 
    return new File('etc.stk').readAsString(); 
} 

myReadAsString().then((s) { 
    // s is **NOT** null here 
} 

另見:

,也許

+0

謝謝@Günter,我認爲建議1或3可能是我正在尋找。爲了提供更多的上下文,我試圖做的是讀入多個文件,將它們處理成單獨的語法樹,並且在讀取塊完成後仍然可以訪問樹。我想我不太清楚「完成」的意思。我會盡力遵循飛鏢道。 –

+0

我將您的評論添加到了您的問題中,並使用我實際測試過的示例更新了我的答案。 –