본문 바로가기
Front-End/Flutter

[Flutter] 08. 시간

by 삼준 2024. 3. 16.
반응형

1. 비동기

플러터에서 비동기 작업을 처리할 때는

 

asyncawait 키워드를 사용함.

 

비동기 함수가 쓰이는 함수에서는 함수명 뒤에 async를 써놔야하고,

 

비동기 함수 앞에는 await를 써놔야 비동기 작업이 제대로 수행됨. 

 

다음은 그 예시임.

// 리턴타입이 없는 경우 void 사용
void main() async {
	print(await createOrderMessage());
}

// 리턴타입이 있는 경우 Future<T> 사용
Future<T> main() async {
	print(await createOrderMessage());
}

2. 프로세스 일시정지

프로세스를 멈추는 방법에는 sleep() 함수와 Future.delayed() 메소드가 있음.

 

sleep 함수는 프로세스 전체를 완전히 중지시키지만,

 

Future.delayed 메소드는 메소드가 사용된 함수만 중지시킨다는 차이가 있음.

 

즉, Future.delayed를 사용하면 뒤에 라인이 먼저 실행됨으로써 비동기적인 작업을 처리할 수 있게 됨.

3. Timer

Timer 클래스는 말그대로 타이머의 역할을 함.

 

뒤에 아무것도 없이 Timer() 로만 쓰면 일정 시간 이후 매개변수로 전달받은 함수를 실행하고,

 

Timer.periodic() 으로 쓰면 일정 시간마다 함수를 반복해서 실행할 수 있음.

 

해당 객체를 cancel 함으로써 필요없는 타이머를 없앨 수 있음.

 

공식 문서 : https://api.flutter.dev/flutter/dart-async/Timer-class.html

 

Timer class - dart:async library - Dart API

A countdown timer that can be configured to fire once or repeatedly. The timer counts down from the specified duration to 0. When the timer reaches 0, the timer invokes the specified callback function. Use a periodic timer to repeatedly count down the same

api.flutter.dev

반응형

'Front-End > Flutter' 카테고리의 다른 글

[Flutter] 10. 토스트, 스낵바  (1) 2024.03.16
[Flutter] 09. 카메라  (0) 2024.03.16
[Flutter] 07. Row, Column, GridView  (0) 2024.03.16
[Flutter] 06. 버튼, 잉크웰  (0) 2024.03.16
[Flutter] 05. 색상  (0) 2024.03.16

댓글