CATCHV Blog

[flutter] AnimatedPositioned repeat animation 본문

Dev/flutter

[flutter] AnimatedPositioned repeat animation

catchv 2022. 12. 5. 14:01
반응형

Stack에서 AnimatedPositioned을 사용하는 경우 상태 변화를 주는 작업이 필요합니다. 

 

아래와 같이 페이지가 로드 되면 자동으로 반복해서 애니메이션을 처리하고 싶을때  처리입니다.

 

 

AnimatedPositioned(
  top: _ani ? -20 : -10,
  duration: const Duration(milliseconds: 500),
  curve: Curves.linear,
  onEnd: () {
    setState(() {
      _ani = !_ani;
    });
  },
  child: BubbleBox(
    width: (width! * 0.5),
    height: 20,
  ),
),

OnEnd로 _ani의 값을 true, false 처리하여 애니메이션 효과를 줄 수 있지만 처음 트리거 하는 변경점이 필요합니다.

flutter.dev의 샘플에서는 위젯을 클릭하는 것으로 처리 하고 있습니다.

 

flutter의 StatefulWidget의 lifecycle을 보면

* 위젯 생성시

Constructor(StatefulWidget) - createState() - Constructor(State<TodayMenu>) - initState() - didChangeDependencies() - Build()

 

* 페이지 refresh(소스 저장)

didUpdateWidget() - Build()

 

* 상태 변경시( setState 호출 )

setState() - Build()

 

처음 build 후에 자동으로 한번만 실행되는 것이 필요한데 override 할 수 있는 함수가 존재하지 않습니다.

GetX를 사용한다면 Controller의 OnReady()를 override해서 처리가 가능합니다.

  @override
  void onReady() {
    super.onReady();
    ani.value = !ani.value;
  }

GetX의 Controller를 보면 onReady()를 다음과 같이 호출하고 있습니다.

abstract class GetNotifier<T> extends Value<T> with GetLifeCycleBase {
  GetNotifier(T initial) : super(initial) {
    $configureLifeCycle();
  }

  @override
  @mustCallSuper
  void onInit() {
    super.onInit();
    ambiguate(SchedulerBinding.instance)
        ?.addPostFrameCallback((_) => onReady());
  }
}

StatefulWidget 을 사용한다면 아래와 같이 처음 시작시 build이후에 호출되는 함수를 작성할 수 있습니다.

  @override
  void initState() {
    super.initState();

    SchedulerBinding.instance
        ?.addPostFrameCallback((_) => onReady(_));
  }
  
    void onReady(_) {
    setState(() {
      _ani = !_ani;
    });
  }

 

 

 

반응형
Comments