Dart非同期処理を実装する方法についてソースコード付きでまとめました。
【Dart】async/awaitによる非同期処理の実装
非同期処理と同期処理の違いは以下のとおりです。
| 種別 | 概要 |
|---|---|
| 非同期処理 | あるタスクの実行中に、他のタスクが別の処理を実行できる方式。 |
| 同期処理 | あるタスクの実行中に、他のタスクの処理は中断される方式。 |
DartではFuture/async(JavaScriptでいうPromise)と「await」もしくは「then」で非同期処理を実装できます。
ただし、thenのほうが可読性が低いためasync/awaitのほうが使いやすいです。
【サンプルコード】使用例
タイムスタンプをコンソールに表示し、10秒後の再度タイムスタンプをコンソールに表示するソースコードです。
awaitの例
import 'dart:async'; // dart:asyncをインポート
// 実行箇所にasyncを宣言
void main() async {
print(new DateTime.now());
// new Future.delayed() の前にawaitを書く
var now = await myfunc();
print(now);
}
Future <String> myfunc(){
return new Future.delayed(new Duration(seconds: 10), (){
return new DateTime.now().toString();
});
}
/*
2019-07-27 08:34:52.262
2019-07-27 08:35:02.264
/*
thenの例
import 'dart:async';
void main() async {
print(new DateTime.now());
myfunc()
.then((now) {
print(now);
});
}
Future <String> myfunc(){
return new Future.delayed(new Duration(seconds: 10), (){
return new DateTime.now().toString();
});
}
/*
2019-07-27 08:34:52.262
2019-07-27 08:35:02.264
/*
| – | 関連記事 |
|---|---|
| 1 | ■【Flutter入門】iOS、Android、Windowsアプリ開発 |
| 2 | 【Dart入門】基礎文法とサンプルコード集 |

コメント