DEV/flutter (dart)

Flutter 자식 위젯에서 부모 위젯 함수에 매개변수 전달하기

석봉 2023. 2. 6. 11:52

1. 부모 위젯에서 함수 선언시 매개변수 만들어두기

2. 자식 위젯에 부모 위젯 함수 등록해주기

3. 자식 위젯에서 부모 위젯의 함수를 사용하고 싶을 때, 선언한 함수 호출하면서 매개변수 넣어주기

4. 부모 위젯에서 등록한 매개변수가 로직에 따라 처리.

// 부모 위젯(ParentWidget)
...(대충 위젯 구성)
var accounts = [];

// 받을 매개변수(dataObj)
addAccount(dataObj) {
  setState(() {
    accounts.add(dataObj);
  });
}

return ChildWidget(notifyParent: addAccount);  // 변수를 parameter로 넘겨주기


// 자식 위젯(ChildWidget)
class ChildWidget extends ...Widget {
  // 부모에서 던진 function parameter 등록 ()
  ChildWidget({Key? key, required this.notifyParent}) : super(key: key);
  final notifyParent;
  
  // notifyParent 사용가능!
  ... (대충 버튼 눌렀을 때...)
  TextButton(onPressed: (){
    ...
    // 매개변수 넣어주기
    notifyParent({'name': name, 'data':data});
  }
  ...
}