[Flutter] Future async & await 사용법

2020년 10월 04일 by 진아사랑해

    [Flutter] Future async & await 사용법 목차
반응형

비동기 방식은 인터넷에서 데이터를 가져오거나 주변기기 I/O를 사용하는 등의 시간이 많이 걸리는 작업에

효율성을 높이기 위해 사용된다

 

import 'dart:async';

 

void printDailyNewsDigest() {

  var newsDigest = gatherNewsReports();  <= Future class 함수이나 바로 return되어 정상적인 값이 없다
  print(newsDigest);
}

 

main() {
  printDailyNewsDigest();
  printWinningLotteryNumbers();
}

 

printWinningLotteryNumbers() {
  print("WinningLotteryNumbers");
}
const news = '<gathered news goes here>';
const oneSecond = Duration(seconds: 1);

 

// 1초 후에 news를 return 
Future<String> gatherNewsReports() => 
  Future.delayed(oneSecond, () => news);

=> 이렇게 하면 1초 후에 Future instance

                    WinningLotteryNumbers 가 출력된다.

 

void printDailyNewsDigest() async {

  var newsDigest = await gatherNewsReports(); 
  print(newsDigest); 
}

async & await를 사용하면 WinningLotteryNumbers

                      1초 후에 <gathered news goes here> 가 출력된다.

 

또 다른 방법으로 Future API를 사용하는 방법이 있다

void printDailyNewsDigest() {

  var newsDigest = gatherNewsReports(); 

  newsDigest.then((value) => {

    print(value)

  });

}

newsDigest인 Future가 value로 return되면 그때 print한다

then을 사용하면 WinningLotteryNumbers

          1초 후에 <gathered news goes here> 가 출력된다.

 

asyn & await에서 에러를 잡는 방법은 try & catch를 사용

void printDailyNewsDigest() {

  try{
  var newsDigest = await gatherNewsReports();
  print(newsDigest);
  }catch(e) {
    print(e.toString());
  }

}

 

Future API 사용에서 에러를 잡는 방법은

void printDailyNewsDigest() {

  var newsDigest = gatherNewsReports(); 

  newsDigest.then((value) => {

    print(value)

  });

  newsDigest.catchError((e) => {

    print(e)

 });

}

 

반응형

'flutter' 카테고리의 다른 글

[Flutter] BuildContext  (0) 2020.10.04
[Flutter] Stream 사용법  (0) 2020.10.04
[Flutter] ChangeNotifier provider 사용법  (0) 2020.10.03
[Flutter] CustomPaint 사용법  (0) 2020.10.02
[Flutter]Form, Global Key, TextFormField 사용  (0) 2020.10.02