gpt4 book ai didi

dart - 使用 rootBundle 加载文件

转载 作者:IT王子 更新时间:2023-10-29 06:46:14 26 4
gpt4 key购买 nike

我需要从文件中加载一个字符串。以下代码始终返回 null:

static String  l( String name ) {

String contents;

rootBundle
.loadString( 'i10n/de.yaml' )
.then( (String r) { contents = 'found'; print( 'then()' ); })
.catchError( (e) { contents = '@Error@'; print( 'catchError()' ); })
.whenComplete(() { contents = 'dd'; print( 'whenComplete()' ); })
;

print( 'after' );

if ( null == contents ) {
return '@null@';
}

String doc = loadYaml( contents );

return doc;

}

我已将此添加到 flutter: pupspec.yaml 部分中的部分:

  assets:
- i10n/de.yaml
- i10n/en.yaml

i10n/de.yaml 文件存在。

我知道,rootBundle.loadString() 是异步的。因此我附加了 then() 调用 - 假设

(String r)  { contents = 'found'; }

仅当 rootBundle.loadString() 返回的 Future 能够返回值时才会执行。

实际上,该方法总是返回“@null@”。因此,我添加了 print() 语句,输出如下:

I/flutter (22382): after
I/flutter (22382): then()
I/flutter (22382): whenComplete()

好吧,显然 loadString() 的 future 比最终的 print() 语句执行得晚。

问:但是我如何强制 future 执行,以便我可以检索它的值?

换句话说:我如何在特定代码中包装一些异步内容以立即检索其值?

PS:flutter/dart 的第一天。可能是一个微不足道的问题...

最佳答案

.then() 正在执行,但在主体的其余部分之后。正如您提到的 loadString() 返回一个 future ,所以在未来完成。要等待 Future 完成,请使用 await。 (请注意,当您将函数标记为异步时,该函数现在必须返回一个 Future 本身 - 因为它必须等待 loadString 在将来完成,所以它本身必须在将来完成......)当你调用 l('something') 你将不得不等待结果。

Future<String> l(String name) async {
try {
String contents = await rootBundle.loadString('i10n/de.yaml');

return contents == null ? '@null@' : loadYaml(contents);
} catch (e) {
return 'oops $e';
}
}

由于必须等待(有很多等待 - 文件读取、http 请求完成等),您的许多实用程序函数变为 async 没什么大不了的.你最终会以类似的方式(从 initState 调用它)

refresh(String s) {
l(s).then((r) {
setState(() {
i18nStuff = r;
});
});
}

当 i18nStuff 准备就绪时设置您的 Widget 的状态,并且在其构建中具有此功能的 Widget 会在准备好之前的几毫秒内在虚拟 UI 和真实 UI 之间切换。

Widget build() {
if (i18nStuff == null) {
return new Container();
}

return new Column(
// build the real UI here
);
}

关于dart - 使用 rootBundle 加载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51341055/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com