如何在Dart中执行下一个代码之前等待代码执行?

时间:2018-08-22 23:07:00

标签: dart flutter

我正在FlutterDart中开发墙纸应用程序。目前,我正在使用“设置墙纸”按钮,需要检查墙纸文件是否存在,如果需要下载该文件,然后更改墙纸。

这就是我现在所拥有的,我认为我做对了,请注意,我和Android Java Developer仅有大约6个月的经验,因此我不了解{{1} }也不是太好。

下载墙纸功能

Dart

设置墙纸功能

static Future<int> downloadWallpaperFile(int wallpaperID,
  {String path}) async {
///Prepare a url for downloading the wallpaper using the getWallpaperURL method and passing in fullSizedWallpaper string constant
String url = getWallpaperURL(WallpaperSize.fullWallpaper, wallpaperID);

///Log output
print('CallingDownloadWallpaper : ' + url);

///Visual Feedback
wallpaperDetailsPageScaffoldGlobalKey.currentState.showSnackBar(
    new SnackBar(content: new Text('Starting Wallpaper Download...')));

///Start downloading the wallpaper file from the url
var data = http.readBytes(url);

///After download is completed
data.then((buffer) async {
  ///If filePath is not passed in as parameter
  if (path == null) {
    ///Use getPathForWallpaperFile to get a path for a wallpaper file
    path = await getPathForWallpaperFile(url);
  }

  ///Create a new file at the path, the path also includes the name of the file which is the id of the wallpaper
  File newFile = new File(path);

  ///Get write access to the newly created wallpaper file
  RandomAccessFile rf = newFile.openSync(mode: FileMode.write);

  ///Write the downloaded data to the file synchronously
  rf.writeFromSync(buffer);

  ///Save the file to the disk synchronously
  rf.flushSync();

  ///Close access to file synchronously
  rf.closeSync();

  ///Log output
  print('DownloadWallpaperResult : Complete');

  ///Visual Feedback
  wallpaperDetailsPageScaffoldGlobalKey.currentState.showSnackBar(
      new SnackBar(content: new Text('Wallpaper Download Complete')));
});
return 0;
}

1 个答案:

答案 0 :(得分:1)

问题在于您正在使用then,这是非阻塞的(基本上是使用Future而不使用await的旧方法)。

相反,请使用await

static Future<int> downloadWallpaperFile(int wallpaperID, {String path}) async {
  // ...

  //Start downloading the wallpaper file from the url
  final buffer = await http.readBytes(url);

  //After download is completed

  //If filePath is not passed in as parameter
  if (path == null) {
    //Use getPathForWallpaperFile to get a path for a wallpaper file
    path = await getPathForWallpaperFile(url);
  }

  // ...

  return 0;
}

顺便说一句,///保留用于类和字段的文档,请使用//进行方法内注释!

我也不确定使用同步io操作是否是一个好主意。那样可能会阻塞应用程序的UI,最好使用async io api(再次使用await)。