[Flutter]Inherited Widget 으로 전역 변 수 를 구현 합 니 다.

3264 단어 전단Flutter
최근 에는 플 루 터 를 이용 해 플랫폼 을 뛰 어 넘 는 앱 을 만 드 는 것 을 연구 하고 있 습 니 다.앞서 자바 로 안 드 로 이 드 애플 리 케 이 션 을 만 드 는 것 을 연 구 했 고 자바 언어 에 도 익숙 하 며 플 루 터 는 Dart 언어 로 만 들 었 기 때문에 Dart 언어 와 Flutter 프레임 워 크 를 익히 는 과정 에서 도 많은 문제 가 발생 했 습 니 다.
인터넷 의 자료 와 공식 문 서 를 많이 봤 는데 Dart 는 전역 변 수 를 지원 하지 않 는 것 같 습 니 다.그리고 Flutter 는 모든 것 을 Widget 으로 추상 화하 고 상태 가 있 는 StatefulWidget 과 상태 가 없 는 StatelessWidget 으로 나 누 었 습 니 다.모든 컨트롤 의 변 수 는 상태 state 로 추상 화 되 었 습 니 다.상태 가 있 는 state 가 바 뀌 면 컨트롤 을 새로 고 쳐 서 변 하 는 목적 을 달성 합 니 다.따라서 문 제 는 여러 컨트롤 이 공유 하 는 state 를 어떻게 정의 하 느 냐 로 바 뀌 었 다.예 를 들 어 Flutter 가 제공 하 는 Inherited Widget 은 전역 변수 와 유사 한 기능 을 실현 할 수 있다.
 
1.InheritedWidget
Inherited Widget 은 작은 위 젯 의 기본 클래스 로 Widget 트 리 에서 정 보 를 효과적으로 전달 하 는 데 사 용 됩 니 다.Inherited Widget 의 하위 컨트롤 은 조상 노드 에서 가장 가 까 운 Inherited Widget 컨트롤 을 자동 으로 찾 고 Inherited Widget 컨트롤 의 변 수 를 가 져 옵 니 다.따라서 전역 변 수 는 Inherited Widget 에 만 정의 해 야 합 니 다.이 변 수 를 공유 해 야 하 는 조상 노드 로 Inherited Widget 컨트롤 을 사용 하면 됩 니 다.
다음은 정부 가 제공 한 예 를 살 펴 보 자.
class FrogColor extends InheritedWidget {
  const FrogColor({
    Key key,
    @required this.color,
    @required Widget child,
  }) : assert(color != null),
       assert(child != null),
       super(key: key, child: child);

  final Color color;

  static FrogColor of(BuildContext context) {
    return context.inheritFromWidgetOfExactType(FrogColor) as FrogColor;
  }

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

그 중에서 Color 는 공 유 된 변수 입 니 다.
of 방법 은 정적 인 방법 입 니 다.이 방법 은 BuildContext.inheritFromWidgetOfExactType 을 호출 하여 FrogColor 위 젯 을 되 돌려 줍 니 다.물론 저 장 된 공유 변수 Color 와 같은 데 이 터 를 되 돌려 줄 수도 있 습 니 다.
updateShouldNotify 방법 은 이 컨트롤 의 리 셋 논리 입 니 다.위의 방법 체 는 color 의 값 이 바 뀌 었 을 때 컨트롤 을 리 셋 하 는 것 을 표시 합 니 다.
 
2.공유 가 변 변수
공식 적 으로 제공 하 는 예 는 final 로 장식 되 어 있 기 때문에 하위 컨트롤 은 값 을 바 꿀 수 없습니다.변 할 수 있 는 변 수 를 만 들 려 면 우리 가 처음에 언급 한 state 를 사용 하여 Inherited Widget 에 Stateful Widget 을 저장 하면 이 Stateful Widget 을 통 해 저장 할 변 수 를 관리 할 수 있 습 니 다.
class _SharedInherited extends InheritedWidget {
  _SharedInherited({
    Key key,
    @required Widget child,
    @required this.data,
  }) : super(key: key, child: child);

  final SharedInheritedWidgetState data;    //    StatefulWidgetState     

  @override
  bool updateShouldNotify(_SharedInherited oldWidget) {    //    
    return data != oldWidget.data;
  }
}

class SharedInheritedWidget extends StatefulWidget {
  SharedInheritedWidget({
    Key key,
    this.child,
  }) : super(key: key);

  final Widget child;

  @override
  SharedInheritedWidgetState createState() =>
      new SharedInheritedWidgetState();

  static SharedInheritedWidgetState of(BuildContext context) {
    return (context.inheritFromWidgetOfExactType(_SharedInherited)
    as _SharedInherited)
        .data;
  }
}

class SharedInheritedWidgetState extends State {
  String _sharedVal = '';    //    

  void setSharedVal(String newVal) {
    setState(() {
      _sharedVal = newVal;
    });
  }

  String getSharedVal() {
    return _sharedVal;
  }

  @override
  Widget build(BuildContext context) {
    return _SharedInherited(child: widget.child, data: this);
  }
}

좋은 웹페이지 즐겨찾기