Flutter - #48. CircularProgressIndicator

Pearl Lee·2022년 2월 27일
1

Flutter Widget

목록 보기
46/50

Flutter 일기
참고 : Flutter.dev - material - CircularProgressIndicator






CircularProgressIndicator

앱 진행상황을 나타낼 때 가장 많이 사용되는 위젯. 원형(Circular)과 선형(Linear) 2가지 Indicator 를 주로 쓴다. 사용법은 거의 동일하다시피 하다. 저번 FutureBuilder 일기에서 한번 사용해본 적이 있는데, 데이터가 오는 중이라는 표시를 CircularProgressIndicator로 하였다.
오늘은 CircularProgressIndicator의 속성을 알아보도록 하겠다.




우선 CircularProgressIndicator를 표시할 때, 두 가지 형태로 나뉜다.

1. Determinate.

특정한 값을 갖는 것인데, CircularProgressIndicator의 value 속성을 활용하는 것이다. 0.0에서 1.0사이의 값을 value에 설정한다.

특정 값으로 고정해도 되긴 한데, 고정해버리면 위젯 자체도 움직이지 않는다. 아래는 value 값을 0.6으로 준 상태이다. 저기서 상태가 전혀 변하지 않는다.

따라서, 0에서 특정 값까지의 진행률(변화)을 나타내주려면 value에 뭔가 변화하는 값을 주어야한다. Controller가 필요한 부분...


2. Indeterminate.

value값을 특정하지 않아서, 진행률이 얼마나 되는지 표시하지 않는다. 아직 진행중... 만 표시하는 것이다.

아직 데이터 안왔어요~ 만 표시하고 싶으면

CircularProgressIndicator()

이렇게 위젯 표시하면 사실상 끝이다.







코드 예시로 알아보자

3. Indeterminate 코드

먼저 indeterminate 형식부터 만들어보았다.

 
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: SizedBox(
          width: 300,
          height: 300,
          child: Stack(
            fit: StackFit.expand,
            children: const [
              CircularProgressIndicator(
                strokeWidth: 10,
                // backgroundColor: Colors.black,
                // color: Colors.green,
              ),
              Center(
                  child: Text(
                'My Progress Indicator',
                style: TextStyle(fontSize: 20),
              )),
            ],
          ),
        ),
      ),
    );
  }

위의 코드에서 주석친 부분을 해제하고 실행하면 아래와 같다.

img 태그의 활용법을 이제 알다니...
위젯 내부의 속성을 조금씩 건드려보면, 다음과 같다.

backgroundColor 해제backgroundColor, color 둘다 해제

4. Determinate 코드

class _MyStatefulWidget extends State<MyStatefulWidget> with TickerProviderStateMixin {

  late AnimationController controller;
  late Animation<Color?> _colorTween;
  
  void initState() {
    controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 10),
    )..addListener(() {
        setState(() {});
      });
      
    _colorTween = controller.drive(ColorTween(begin: Colors.yellow, end: Colors.blue));
    controller.forward();
    super.initState();
  }

  
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: SizedBox(
          width: 300,
          height: 300,
          child: Stack(
            fit: StackFit.expand,
            children: [
              CircularProgressIndicator(
                strokeWidth: 10,
                value: controller.value,
                valueColor: _colorTween,
              ),
              Center(
                child: Text(
                  (controller.value * 100).toInt().toString(),
                  style: TextStyle(fontSize: 30),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

이번에는 value 값을 AnimationController로 설정하고, 색도 value 에 맞게 변화하도록 ColorTween을 만들어보았다. 이 코드는 공식 페이지의 예제를 가져다가 변형한 것이다.

  AnimationController({
    double? value,
    this.duration,
    this.reverseDuration,
    this.debugLabel,
    this.lowerBound = 0.0,
    this.upperBound = 1.0,
    this.animationBehavior = AnimationBehavior.normal,
    required TickerProvider vsync,
  })

AnimationController를 AnimatedBuilder 일기 쓸 때 본 적 있지만, 사용법을 까먹었다. 다시 보면 lowerBound, upperBound가 각각 0과 1로 설정된 것을 알 수 있다. Controller의 value는 0부터 1까지 변하는 것이다. 얼마 동안? duraion에 설정된 시간 동안.

그렇다면 여기의 코드는, 10초 동안 value는 0에서 1까지로 변한다.
Stateful 위젯이므로, addListener에 setState를 추가해 주었다.

addListener method는 애니메이션의 value 속성이 변할 때마다 호출되는 것이다. value는 AnimationController가 실행되는 10초 동안 계속 변하므로, 10초 동안 setState()가 계속 실행된다는 말이다.
AnimationController의 value를 CircularProgressIndicator.value에 설정하였으므로, CircularProgressIndicator도 setState에 의해 변하게 된다.

_colorTween은 CircularProgressIndicator의 value값이 변함에 따라 색도 변하게 하려고 만들었다.

실행결과는 아래와 같다.

그 동안 CircularProgressIndicator는 사용할 일이 정말 많았다. LinearProgressIndicator 도 사용법이 거의 비슷하므로, CircularProgressIndicator에 대해서만 다루고 넘어가려고 한다.






오늘의 일기는 여기까지!

profile
안 되면 되게 하라

0개의 댓글