Future<ProcessedData> createData() {
return _loadFromDisk().then((id){
return _fetchNetworkData(id);
}).then((data){
return ProcessedData(data);
})
}
Future<ProcessedData> createDate() async {
final id = await _loadFromDisk();
final data = await _fetchNetworkData(id);
return ProcessedData(data);
}
→ 동일한 코드!
마치 동기적으로 실행되는 것처럼 느껴진다.
_loadFromDisk이 완료 되면 그다음 블록을 실행.
await
를 만나면 해당 동작을 완료되기 전까지 멈추어서 기다리기 때문에 then(...)
함수 처럼 동작을 하며 전체적인 코드는 훨씬 가독성이 좋다.
실행 과정
await
를 만나면 함수를 잠시 멈추고 함수를 호출한 곳에 Future
를 return 합니다.await
가 붙은 동작이 완료되기 전까지 함수를 더 이상 진행하지 않습니다.Future
에서 return 값이 나오게 합니다.Future<String> helloWorld() {
// 3초 후에 Future<String> 에서 "Hello World" 가 나옵니다
return Future.delayed(Duration(seconds: 3), () {
final hello = "Hello World";
print(hello);
return hello;
});
}
void main() {
final future = helloWorld();
print(future);
}
출력 결과
Instance of 'Future<String>'
Hello World
→ 비동기적으로 처리되기 때문
await을 붙인다면?
Future<String> helloWorld() {
return Future.delayed(Duration(seconds: 3), () {
final hello = "Hello World";
print(hello);
return hello;
});
}
void main() async {
final future = await helloWorld();
print(future);
}
Hello World
Hello World
class _MyHomePageState extends State<MyHomePage> {
Future<String> future;
Future<String> helloWorld() {
return Future.delayed(Duration(seconds: 15), () {
return 'Hello World';
});
}
void initState() {
super.initState();
future = helloWorld();
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: FutureBuilder<String>(
future: future,
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
if (snapshot.hasData) {
return Text('스냅샷 데이터: ${snapshot.data.toString()}');
} else if (snapshot.hasData == false) {
return CircularProgressIndicator();
} else if (snapshot.hasError) {
return Text('스냅샷 에러');
} else {
return Text('혹시 몰라서 else문 추가');
}
},
),
),
);
}
}