Flutter- 데이터 전달 방법

yezee·2024년 9월 8일
0

Flutter

목록 보기
15/15
post-thumbnail

대부분의 프로그래밍 언어는 부모(상위)에서 자식(하위)로 데이터를 전달하는 단방향 데이터 흐름 방식이 일반적이고 데이터 전달,props전달 이라고 부른다

반대로, 자식에서 부모로 데이터를 전달하거나 부모가 자식의 함수를 실행하도록 하는 패턴을 콜백이라고 부르고 이는 역방향 통신을 가능하게 해준다

역방향 통신

globalKey

  1. 부모위젯(ParentWidget)
    GloabalKey<_childWidgetState> 키이름= Gloabalkey()를 통해 자식 위젯의 상태에 접근할 수 있도록 설정
    _childkey.currentState?.childFunction();을 통해 자식이 childFunction을 호출

  2. 자식위젯()
    statefulWidget을 사용해서 childFucntion이라는 함수를 정의

부모위젯

class ParentWidget extends StatefulWidget {
  
  _ParentWidgetState createState() => _ParentWidgetState();
}
class _ParentWidgetState extends State<ParentWidget> {
  // 자식 위젯의 상태에 접근하기 위한 GlobalKey 생성
  final GlobalKey<_ChildWidgetState> _childKey = GlobalKey<_ChildWidgetState>();

  
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          // 자식 위젯에 GlobalKey 전달
          ChildWidget(key: _childKey),
          ElevatedButton(
            onPressed: () {
              // 자식 위젯에서 정의한 함수 호출
       _childKey.currentState?.childFunction();
            },
            child: Text('Call Child Function'),
          ),
        ],
      ),
    );
  }
}
자식위젯

class ChildWidget extends StatefulWidget {
  const ChildWidget({Key? key}) : super(key: key);

  
  _ChildWidgetState createState() => _ChildWidgetState();
}

class _ChildWidgetState extends State<ChildWidget> {
  // 자식 위젯에서 정의한 함수
  void childFunction() {
    print("자식 위젯에서 동작하는 함수입니다.");
  }

  
  Widget build(BuildContext context) {
    return Container(
      child: Text('자식 위젯'),
    );
  }
}

콜백함수 사용

부모위젯이 자식 위젯에 콜백함수를 전달하고 , 자식 위젯이 콜백함수를 호출하는 방법

상태관리 라이브러리 사용

상태 관리 라이브러리를 사용하여 부모와 자식 위젯 간의 상태를 공유하고, 자식 위젯에서 상태를 변경함으로써 부모에서 그 변화를 감지할 수 있습니다. 예를 들어, Provider, Riverpod, Bloc 등

===> Flutter 상태관리 라이브러리

profile
아 그거 뭐였지?

0개의 댓글