Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Dart 使用rootBundle加载文件_Dart_Flutter - Fatal编程技术网

Dart 使用rootBundle加载文件

Dart 使用rootBundle加载文件,dart,flutter,Dart,Flutter,我需要从文件中加载一个字符串。以下代码始终返回null: static String l( String name ) { String contents; rootBundle .loadString( 'i10n/de.yaml' ) .then( (String r) { contents = 'found'; print( 'then()' ); }) .catchError( (e) { contents = '@Error@';

我需要从文件中加载一个字符串。以下代码始终返回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;

  }
我已将此添加到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()的未来执行时间晚于最终的print()语句

Q:但我如何强制未来执行,以便找回它的价值呢?

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

附:飞镖/飞镖的第一天。可能是个小问题……

执行
.then()
,但要在身体的其余部分之后执行。正如您所提到的
loadString()
返回未来,因此在未来完成。要等待将来完成,请使用
wait
。(请注意,当您将函数标记为async时,函数现在必须返回一个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';
  }
}
在i18nStuff准备就绪时设置小部件的状态,并且在构建中包含该状态的小部件在虚拟ui之间切换几毫秒,直到它准备就绪,然后切换到真实ui

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

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

谢谢!在某个特定的代码点上,没有办法等待未来的完成?好的,我明白了。代码应该加载本地化字符串。我需要它们显示第一个小部件。然后我是否应该异步加载资源,并将应用程序/小部件的创建放在顶层的then()部分?您可以使
main()
async并在那里加载内容,但更好的是,请参见编辑的答案
Widget build() {
  if (i18nStuff == null) {
    return new Container();
  }

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