투케이2K

45. (Flutter/플러터) [Mac] : [Dart] : 다트 - Future 사용해 비동기 작업 처리 및 Callback 콜백 응답 확인 본문

Flutter

45. (Flutter/플러터) [Mac] : [Dart] : 다트 - Future 사용해 비동기 작업 처리 및 Callback 콜백 응답 확인

투케이2K 2024. 5. 28. 19:42
반응형

[개발 환경 설정]

개발 툴 : AndroidStudio

개발 언어 : Dart

 

[소스 코드]

import 'package:flutter/material.dart';
import 'dart:developer';


// -----------------------------------------------------------------------------------------
// TODO [main] : [application 의 진입점 역할]
// -----------------------------------------------------------------------------------------
void main() {

  /**
   * ------------------------------------------------
   * [요약 설명]
   * ------------------------------------------------
   * 1. Future : 자바스크립트에서의 Promise 와 유사하며, 비동기 작업을 수행할 때 사용 됩니다
   * ------------------------------------------------
   * 2. 비동기 작업은 해당 작업이 완료되기 전에도 다른 작업을 실행할 수 있게 합니다
   * ------------------------------------------------
   * */


  // [로직 처리 수행]
  try {

    // [future 비동기 함수 호출]
    Future<String> future = futureString();

    // [비동기 함수 호출 로직 처리 후 결과 확인]
    future.then((val) {
      log("");
      log("-------------------------------------------------------");
      log("Future Callback :: ${val}");
      log("-------------------------------------------------------");
      log("");
    }).catchError((error) {
      log("");
      log("-------------------------------------------------------");
      log("Future Error :: ${error}");
      log("-------------------------------------------------------");
      log("");
    });

    log("");
    log("-------------------------------------------------------");
    log("Program :: Start");
    log("-------------------------------------------------------");
    log("");

  }
  catch (e) {
    log("");
    log("-------------------------------------------------------");
    log("Catch :: ${e}");
    log("-------------------------------------------------------");
    log("");
  }

}





// -----------------------------------------------------------------------------------------
// TODO [Future] : 비동기 처리 함수 선언
// -----------------------------------------------------------------------------------------
Future<String> futureString() {

  // -----------------------------------------------

  // [delayed] : 3초 지연 설정
  return Future<String>.delayed(Duration(seconds: 3), () {
    return "Future :: End";
  });

  // -----------------------------------------------

  // [에러 응답 반환]
  /*
  return Future.delayed(const Duration(seconds: 3),
      () => throw Exception("Future :: Exception"));
  // */

  // -----------------------------------------------

}
 

[결과 출력]

 

 

반응형
Comments