http://www.flutterbyexample.com/#/posts/build_context
Flutter by Example
www.flutterbyexample.com
위의 글을 번역(의역) 했습니다.
"BuildContext 이란?" 간단한 설명
- widget 트리 에서 Widget 의 위치.
- 부모 widget 의 build 메소드가 리턴한 context 정보)
build 메소드 안의 context 와 클레스 안에 있는 context 는 동일한거가 아닙니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
class _MyHomePageState extends State<MyHomePage> {
_MyHomePageState() {
print(context.hashCode);
// prints 2011
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Container(),
floatingActionButton:
new FloatingActionButton(onPressed: () => print(context.hashCode)),
// prints 63
);
}
}
|
- 잘못된 context ,build 를 사용하기 쉬우니 조심해야함. ( of(context) 를 사용하면 알수있음 )
- of(context) 메소드를 통해서 그 widget 정보를 가져올수 있음.
The 'of()' Method
플러터에서는 모든게 widget 이다, 위젯 트리구조 에서 다른 위젯을 참조하기 위해선 약간의 기능이 필요로 하다.
특히 상속한 위젯들을 참조하기 위해서는 "of()" 메소드 형태를 사용한다.
1
2
3
4
5
6
|
@override
Widget build(context) {
return new Text('Hello, World',
style: new TextStyle(color: Theme.of(context).primaryColor),
);
}
|
부모 Widget 의 'Theme' Widget primaryColor 값을 가져오는 소스(build 메소드의 context 가 부모와의 관계를 알수 있음)
'Flutter' 카테고리의 다른 글
Inherited Widgets 상속된 위젯 (0) | 2020.02.12 |
---|