개발 공부/FLUTTER

[Flutter] InheritedWidget이란?

애해 2024. 8. 23. 16:21
728x90

1. 왜 필요하나?

- 불필요한 데이터 전달을 방지하고 트리의 root에 접근해 바로 데이터를 가져오기 위해서!

StatefulWidget과 StatelessWidget을 통해 화면을 구성하게 되면 데이터의 변경이 필요한 위젯이 트리구조의 끝부분에 있을 경우 트리의 Top에서 Bottom가지 불필요한 데이터 전달이 일어난다. 

 

 

데이터의 변경이 필요한 위젯이 트리의 Top에 바로 접근하여 데이터를 가져올수 있게 하는 widget이 InheritedWidget이다. 상태관리 라이브러리의 기본이 되는 Provider의 핵심이다. 

 

 

 

2. InheritedWidget 예시

class FrogColor extends InheritedWidget {
  const FrogColor({
    super.key,
    required this.color,
    required super.child,
  });

  final Color color;

  static FrogColor? maybeOf(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<FrogColor>();
  }

  static FrogColor of(BuildContext context) {
    final FrogColor? result = maybeOf(context);
    assert(result != null, 'No FrogColor found in context');
    return result!;
  }

  @override
  bool updateShouldNotify(FrogColor oldWidget) => color != oldWidget.color;
}

 

InheritedWidget을 상속받으면 반드시 override해야하는 메소드가 있는데 updateShouldNotify이다. updateShouldNotify는 상속받은 위젯이 있을 경우 모든 상황에서 재빌드되는것을 방지하기 위해 설정해준다. 빌드가 필요한 경우 true, 빌드가 필요없는 경우 false로 설정하면 끝! 

 

Of() 와 Maybe Of() ?

of() 경우 null 아닌 인스턴스를 반환하고 상속된 widget 찾을 없는 경우 오류를 발생시킨다. mayOf()는 null 아닌 인스턴스를 반환하지만 widget 찾을 없는 경우 null 반환한다. 

 

 

# 출처 

https://api.flutter.dev/flutter/widgets/InheritedWidget-class.html

 

InheritedWidget class - widgets library - Dart API

Base class for widgets that efficiently propagate information down the tree. To obtain the nearest instance of a particular type of inherited widget from a build context, use BuildContext.dependOnInheritedWidgetOfExactType. Inherited widgets, when referenc

api.flutter.dev

 

반응형