2014-05-14 52 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

我将您的评论添加到了您的问题中,并使用我实际测试过的示例更新了我的答案。 –