[Flutter]Inherited Widget 으로 전역 변 수 를 구현 합 니 다.
인터넷 의 자료 와 공식 문 서 를 많이 봤 는데 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);
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
전단 자동화 워 크 플 로 의 hooks예 를 들 어 우 리 는 git commt 전에 eslint 코드 검사, npm install 전에 프로젝트 의존 도 를 검사 하고 싶 습 니 다.전형 적 인 상황 에서 각종 도 구 는 특정한 동작 이 발생 할 때 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.