개요
기본적으로 부모 위젯에서 자식 위젯의 메소드를 호출할 수 있는 방법은 따로 없습니다. 하지만 불가능한것은 아니죠. 오늘은 그것에 대해서 알아보도록 하겠습니다.
Controller
부모 - 자식 위젯간에 Controller를 하나 두는 방법입니다. 부모 위젯에서 Controller를 생성하고 자식 위젯에게 전달해 메소드를 주입받는 방식이죠.
class TimerController {
late Function() start;
late Function() stop;
}
먼저 이렇게 Controller를 만듭니다.
class MainPage extends StatefulWidget {
const MainPage({super.key});
@override
State<MainPage> createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
final TimerController _timerController = TimerController();
@override
Widget build(BuildContext context) {
return CustomTimerWidget(
controller: _timerController,
);
}
}
부모위젯에서 자식위젯에 TImerController를 주입해줍니다.
class CustomTimerWidget extends StatefulWidget {
TimerController? controller;
CustomTimerWidget({super.key, this.controller});
@override
State<CustomTimerWidget> createState() => _CustomTimerWidgetState();
}
class _CustomTimerWidgetState extends State<CustomTimerWidget> {
void start() {
print('timer start');
}
void stop() {
print('timer stop');
}
_timerInit() {
widget.controller?.start = start;
widget.controller?.stop = stop;
}
@override
void initState() {
_timerInit();
super.initState();
}
@override
Widget build(BuildContext context) {
return const Placeholder();
}
}
자식 위젯에서 initState 시점에 부모로 부터 받은 controller에 Function을 넣어줍니다.
이제 부모위젯에서 자식 위젯의 메소드를 사용할 수 있게되었습니다.
이 방법은 flutter내에서 정말 많이 사용하고 있는 패턴같습니다. PageView, ListView 등등 다양한곳에서 Controller를 받는걸 볼 수 있습니다. 이 방법말고 GlobalKey를 이용해 자식위젯의 메소드를 사용할 수 는 있지만 같은 파일(.dart) 내에 존재하지 않는다면 사용 할 수 없다는 큰 단점이 있고, GlobalKey를 많이 사용할 수록 복잡해지는 단점이있어서 위와 같은 방식을 추천드립니다.
'Language > Flutter' 카테고리의 다른 글
[Flutter] 도넛차트를 만들어보자 (0) | 2024.11.27 |
---|---|
[Flutter] ConstrainedBox vs SizedBox - 크기 제약의 이해 (0) | 2024.11.25 |
[Flutter] /android/app/src/main/res/mipmap-hdpi/ic_launcher.png: AAPT: error: file failed to compile. 에러 해결방법 (0) | 2024.11.23 |
[Flutter] 앱 아이콘 변경 (0) | 2024.11.22 |
[Flutter] 앱 이름 변경 (0) | 2024.11.21 |