공부방/Flutter

Flutter showModalBottomSheet setState not working (플러터 showModalBottomSheet setState 동작 안하는 현상)

soycrab 2023. 2. 9. 15:04

 

setState()는 StatefulWidget 에서 특정 오브젝트의 상태(값)를 변경하기 위해 사용하는 메소드에요 .

근데 이번에 showModalBottomSheet에서 요일을 선택하는 기능을 가진 화면을 작업하다가

setState 를 통해 상태 변경을 호출해도 화면이 변경되지 않는 현상을 발견했어요.

아래는 문제의 코드에요 

 showModalBottomSheet(
        context: context,
        builder: (context) {
              return Container(
                height: heightOfModalBottomSheet,
                child: RaisedButton(onPressed: () {
                  setState(() {
                    heightOfModalBottomSheet += 10;
                  });
                }),
              );
        });

 

아래는 StatefulBuilder 을 이용한 해결 코드에요 

showModalBottomSheet(
    context: context,
    builder: (context) {return StatefulBuilder(
          builder: (BuildContext context, StateSetter setModalState /*해당 부분 이름을 바꾸어 사용!*/) {
        return Container(
          height: heightOfModalBottomSheet,
          child: RaisedButton(onPressed: () {
            setModalState(() {
              heightOfModalBottomSheet += 10;
            });
          }),
        );
      });
});

 

왜 그런지는 찾아보아야 해요....

출처 : https://stackoverflow.com/a/56972160

반응형