[TIL] Day 66 BuildContext 이해하기

현서·2026년 3월 3일

[TIL] Flutter 9기

목록 보기
78/102

BuildContext 이해하기

빌드 컨텍스트(BuildContext)

핵심 위젯 트리 내 특정 위젯의 위치를 알려주는 객체
역할

  • 부모 위젯 찾기 (context.findAncestorWidgetOfExactType)
  • 테마, MediaQuery, Navigator 등 상위 리소스 접근
  • InheritedWidget 구독

중요 포인트

  • 위젯 자체가 아님 → 불변 상태의 위젯과는 별개
  • Element와 연결되어 있으며, 실제 렌더링 위치를 참조
Widget build(BuildContext context) {
  final theme = Theme.of(context); // 상위 테마 접근
  return Text('Hello', style: theme.textTheme.bodyMedium);
}

Element와의 관계

BuildContext는 내부적으로 Element를 참조

Flutter 구조

Widget (설계도) → Element (트리 내 위치 & 상태) → RenderObject (화면 렌더링)
context → Element → 위젯 트리 탐색 가능

즉, BuildContext를 통해 “내가 트리에서 어디 있는지”를 알 수 있음

InheritedWidget과 컨텍스트

InheritedWidget은 상위 상태를 하위 위젯과 공유할 때 사용
BuildContext를 통해 하위에서 접근 가능:

final data = context.dependOnInheritedWidgetOfExactType<MyInherited>()?.counter;

데이터 변경 시 자동 rebuild → Context가 연결된 위젯만 업데이트

SafeArea와 컨텍스트

SafeArea도 BuildContext를 사용해서 디바이스의 안전 영역 정보(MediaQuery)를 가져옴

return SafeArea(
  child: Text("Hello, World!"),
);

즉, SafeArea는 BuildContext를 통해 화면 정보를 읽고 적용

0개의 댓글