콜백함수
콜백함수는 특정 작업이나 이벤트가 발생했을때 실행되도록 미리 정의해 두는 함수입니다. 다른 함수가 실행을 끝낸 뒤 실행되는 callback함수를 의미합니다. 비동기 작업, 사용자 입력 또는 특정 상태변화에 따라 원하는 동작을 구현하는데 유용합니다.
콜백함수의 개념
콜백 함수는 다른 함수나 위젯에 전달되어 특정 시점에서 호출되는 함수입니다. 보통 버튼 클릭, 사용자 동작, 또는 비동기 작업 완료 시 호출됩니다.
void exampleFunction(Function callback) {
print("Before callback");
callback(); // 전달받은 함수를 호출
print("After callback");
}
// 콜백함수 사용
void main() {
exampleFunction(() {
print("This is the callback function");
});
}
//출력
Before callback
This is the callback function
After callback
Flutter에서 주요 콜백 사용되는 곳
- 버튼 클릭 이벤트
ElevatedButton( onPressed: () { print("Button pressed!"); }, child: Text("Click Me"), ) - TextField에서 입력 변화 감지
TextField( onChanged: (text) { print("Current input: $text"); }, ) - ListView 아이템 클릭
InkWell( onTap: () { print("Item tapped!"); }, child: Container( padding: EdgeInsets.all(16.0), child: Text("Tap me"), ), ) - 커스텀 위젯에서 콜백 전달
// 부모위젯 CustomWidget( onCustomAction: () { print("Custom action performed!"); }, ) // 커스텀 위젯 class CustomWidget extends StatelessWidget { final VoidCallback onCustomAction; CustomWidget({required this.onCustomAction}); @override Widget build(BuildContext context) { return ElevatedButton( onPressed: onCustomAction, child: Text("Trigger Action"), ); } }
콜백 함수의 주요 타입
VoidCallback
- 반환값과 매개변수가 없는 콜백 함수.
- 예: void Function()
final VoidCallback callback = () {
print("Callback triggered!");
};
ValueChanged<T>
- 값 하나를 매개변수로 받고, 반환값이 없는 콜백 함수.
- 예: void Function(T value)
final ValueChanged<String> onChanged = (value) {
print("Value changed to: $value");
};
Function 또는 일반 함수
- 더 복잡한 매개변수와 반환값이 있는 경우.
Function(int a, int b) sumCallback = (a, b) {
return a + b;
};
비동기 콜백 함수
콜백함수는 비동기 작업에서도 주로 사용되며 Future함수와 함께 사용되는 경우가 많습니다.
Future<void> fetchData(Function onComplete) async {
await Future.delayed(Duration(seconds: 2)); // 비동기 작업
onComplete(); // 작업 완료 후 콜백 호출
}
void main() {
fetchData(() {
print("Data fetched!");
});
}
'Flutter' 카테고리의 다른 글
| [FLUTTER] 상태관리 응용 앱 제작 2 - InheritedWidget (1) | 2025.01.21 |
|---|---|
| [FLUTTER] 상태관리 응용 앱 제작 1 - StatefulWidget (2) | 2025.01.20 |
| [FLUTTER] Stack 위젯 (0) | 2025.01.20 |
| [FLUTTER] 기초 화면 구성 (0) | 2025.01.20 |
| [FLUTTER] 위젯(Widget) (0) | 2025.01.20 |