본문 바로가기
Flutter/Flutter 필수개념

[Flutter] Inherited Widget 배우기

by 붕어사랑 티스토리 2021. 12. 16.
반응형

1. Inherited Widget을 쓰는 이유

 

먼저 문제상황부터 인식합시다.

 

Root 위젯에 어떠한 데이터(state)가 있다고 가정합시다.

그리고 가장 아래에 있는 주황색 위젯에서 이를 필요로 합니다.

 

그럼 주황색 위젯에 이 데이터(state)를 넘겨주기 위해 중간과정의 모든 위젯의 생성자에 state 데이터를 뚫어주어야 겠지요.

 

상당히 귀찮은 일입니다.

 

 

생성자에 하나한 데이터를 뚫어주는게 귀찮아서 모든 위젯을 하나의 build메소드에 묶는건 어떨가요?

state값이 바뀌면 주황색 위젯만 바뀌면 되는데 필요없는 중간과정의 위젯들까지 rebuild 됩니다.

성능저하의 문제가 생기겠지요.

 

 

 

 

 

 

그래서 나온 해결책이 바로 Inherited 위젯입니다.

 

가장 위젯트리 최상단에 Inherited 위젯을 놓고 데이터를 저장하면 자식 위젯들은 이를 어디서든지 바로 접근이 가능합니다.

 

 

 

 

 

 

2. of 메소드

 

자 그럼 자식위젯에서 저 Inherited 위젯을 어떻게 접근 할 까요?

 

바로 of 메소드를 이용하는 겁니다.

of메소드를 사용하려면 먼저 BuildContext에 대한 개념을 알아야 하는데요.

 

자세한 내용은 아래 제 블로그에 설명 해 놓았습니다.

 

일단 of 메소드를 사용하면 되는구나! 하고 넘어가시고

이 글을 다 읽으신뒤 BuildContext 학습 하시는걸 추천드립니다.

 

 

 

 

https://lucky516.tistory.com/122?category=1065021 

 

[Flutter] BuildContext 와 of 함수

https://api.flutter.dev/flutter/material/Scaffold/of.html of method - Scaffold class - material library - Dart API ScaffoldState of(BuildContext context ) Finds the ScaffoldState from the closest in..

lucky516.tistory.com

 

반응형

 

 

 

3. InheritedWidget 사용법

 

아래가 구글 공식문서에 나온느 대표적인 사용 예제입니다.

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

  final Color color;

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

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

 

 

 

1. 먼저 Inherited 위젯을 상속합니다.

class FrogColor extends InheritedWidget {

 

2. of 함수를 정의 해 줍니다.

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

 

3. updateShouldNotify 함수를 재정의 해 줍니다.

이 함수는 oldvalue 와 new value를 비교해서 위젯이 redraw 되도록 해 주는 value값을 지정해 주는 메소드입니다.

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

 

 

 

4. Provider

구글에서 이런 Inherited 위젯을 만들긴 했지만 사실 맘에 안들었는지 Provider라는 패키지를 쓰라고 권장 합니다.

 

고로 여러분이 이 글에서 얻어가실거는 Inherited Widget이 왜 탄생했냐 정도만 아시면 됩니다.

 

허무하죠?

 

 

그럼 Provider는 무엇일까요? Provider 또한 아까 처음에 언급했던 문제상황을 해결하기 위한 패키지 입니다.

자식 위젯들이 특정 최상단 데이터에 바로 접근 해 줄 수 있도록 해 주는 라이브러리 이죠.

 

 

Provider의 자세한 내용은 아래에 설명 해 놓았습니다.

 

https://lucky516.tistory.com/121?category=1065021 

 

[Flutter] state 관리와 provider

https://docs.flutter.dev/development/data-and-backend/state-mgmt/declarative Start thinking declaratively How to think about declarative programming. docs.flutter.dev 해당 문서는 플러터 공식 문서를..

lucky516.tistory.com

 

 

 

5. 마지막으로 하나 더 알아야 할 것

 

사실 일부 많은 위젯들은 Inherited Widget 입니다! 대표적인 예로 Scaffold 위젯, Theme 위젯, FocusScope 위젯이 있습니다.

 

그럼 아까 2번에서 배운 내용을 활용하면, 저 위젯들이 부모 위젯에 있으면 of 메소드로 접근할 수 있겠지요?

 

이게 바로 여러분이 이 글에서 알아야 할 두번째 내용입니다.

 

 

 

 

6. 마무리

 

이 글을 읽고 아래 두가지만 반드시 기억하면 좋겠습니다.

 

Inherited Widget이 필요한 이유

일부 특정 위젯들은 사실 Inherited Widget 이라는 것

 

 

읽어주셔서 감사합니다.

반응형

댓글