[Flutter / error] FlutterError (setState() or markNeedsBuild() called during build.

solra·2023년 4월 21일
0

이 오류는 플러터 작업을 하다 보면 종종 마주치게되는 오류인데요

FlutterError (setState() or markNeedsBuild() called during build.
This PageJoinAccount widget cannot be marked as needing to build because the framework is already in the process of building widgets. A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase.
The widget on which setState() or markNeedsBuild() was called was:
PageJoinAccount
The widget which was currently being built when the offending call was made was:
TextFormField)

말 그대로 build가 이뤄지고 있는 동안 setState 를 호출하는 경우 발생하게 됩니다

저는 textfield 의 validator 내에서 setState()를 사용하려다 해당 오류를 발견 했습니다

해결 방법

addPostFrameCallback을 사용해 빌드가 끝난 1프레임 뒤에 실행해주면 됩니다

  String? validator(String? value) {
    ...
      ///validate 동안 setstate 하면 오류 발생하여 setstate 가 필요한 경우 1프레임 뒤에 setstate 해주면 됨
      SchedulerBinding.instance.addPostFrameCallback(
        (_) {
          setstate();
        },
      );
    }

    return message;
  }
profile
현 Flutter 개발자 🥴

0개의 댓글