GlobalKey사용
child Widget 의 State를 GlobalKey 로 전달
key는 무엇인가?
1. 위젯의 state를 보존 ( 예- 체크박스의 상태, 텍스트 필드의 문자들이 입력되고 있는지 등)
2. 위젯을 식별
Global Key : 위젯의 state를 외부 위젯에서 접근
class ChildWidget extends StatefulWidget {
const ChildWidget({Key? key,}) : super(key: key);
@override
State<ChildWidget> createState() => ChildWidgetState();
}
class ChildWidgetState extends State<ChildWidget> {
Color _color = Colors.red;
void changeColor(Color color) {
setState(() {
_color = color;
});
}
@override
Widget build(BuildContext context) {
return InkWell(
child: Container(
width: 200,
height: 200,
color: _color,
child: const Text('Child Widget'),
),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final GlobalKey<ChildWidgetState> _globalKey = GlobalKey();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ChildWidget(
key: _globalKey,
),
const SizedBox(height: 10,),
InkWell(
onTap: () {
_globalKey.currentState?.changeColor(Colors.red);
},
child: Container(
height: 50,
color: Colors.yellow,
child: const Text('Parent Widget Button')
),
)
],
),
),
);
}
}