부모 위젯 상에서 자식 위젯에 정의된 메서드 호출 하는 방법
자식 위젯이 버튼인데 버튼에서 실행하는 메서드도 자식 위젯에 정의가 되어있었다.
이것을 부모 위젯의 어느 버튼을 눌렀을 때도 호출이 될 수 있도록 연결 해야 한다.
글로벌키를 이용하는 방법이 가장 간단하겠지만, 왠지 직접 전역 변수를 선언하고 싶지는 않다...
좀더 세련된 방법이 없을까? 바로 떠오르지 않아 구글링을 해보니 쉽게 찾을 수 있었다.
typedef 을 사용하는 방법
Parent 쪽에 함수를 연결 할 수 있는 변수 y를 정의 해주고 parent의 버튼에서 이 함수 변수를 호출 (y.call) 하도록 만들어 둔다.
그리고 parent 에서 child를 생성할때 함수를 파라미터로 받아 parent의 함수 변수 y 에 연결하는 익명함수를 전달한다.
이 익명 함수를 전달 받은 child 에서는 위젯을 build 할 때 이것을 실행하여 child에서 정의한 함수 x를 이것의 파라미터로 전달한다. 그러면 익명함수에서는 x를 인자로 받은뒤 y에 연결하는 구문을 실행하게 되고, parent의 y는 x와 연결된다.
적용 후기: 동작은 하는데...문제가 있다.
" typedef MyBuilder = void Function(BuildContext context, void Function() methodA); "
를 선언한 파일의 경우, (안드로이드 스튜디오에서) 저 구문 아래의 code에 대해서 Analizer가 분석을 못하는 것같다. 이하의 코드에 대해서 변수나 클래스 정의 바로가기 단축키(ctrl + 우클릭) 같은 것들이 먹히지 않는다.
import 'package:flutter/material.dart';
typedef MyBuilder = void Function(BuildContext context, void Function() methodA);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
late void Function() myMethod;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.help),
onPressed: () {
// how can I call methodA from here?
myMethod.call();
},
),
),
body: HomePage(builder: (BuildContext context, void Function() methodA) {
myMethod = methodA;
},),
),
);
}
}
class HomePage extends StatefulWidget {
final MyBuilder builder;
const HomePage({Key? key, required this.builder}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
widget.builder.call(context, methodA);
return Text('HomePage');
}
void methodA() {
print('test');
}
}
참고자료: https://stackoverflow.com/questions/53692798/flutter-calling-child-class-function-from-parent-class
Flutter calling child class function from parent class
Code: class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( leading: IconButton( ...
stackoverflow.com
changeNotifier class를 사용하는 방법
아래는 자료는 typedef 대신 class 를 사용하는 방법이다. 큰틀에서 보면 비슷하다.
그리고 답변중에 GlobalKey를 사용 하는 바법도 나와있다.
https://stackoverflow.com/questions/72969209/how-to-call-a-method-of-a-child-stateful-widget-flutter
How to call a method of a child stateful widget? FLUTTER
How do I call method of child widget? class Parent extends StatefulWidget { const Parent({Key? key}) : super(key: key); @override State<Parent> createState() => _ParentState(); } c...
stackoverflow.com