티스토리 뷰

개발/Flutter

Flutter : AnimatedBuilder widget

부캐: 개발하는 조대리 2023. 4. 14. 09:00
반응형
 AnimatedBuilder widget은 상태가 없는 단순한 Animation이 필요할 경우 사용합니다.

(보통 사용자에 의한 이벤트 발생 시 Animation 기능을 추가하지만 (복잡도 올라감)
AnimatedBuilder widgtet은 사용자가 설정한 시간 주기로 시스템에서 builder 함수를 호출해 주기 때문에
단순 Animatioin 기능 구현 시 좋을 것 같습니다.)

 

1. 소스코드

아래 AnimatedBuilder 객체 생성하는 부분입니다.

  body: AnimatedBuilder(
    animation: _controller,
    child: Center(
      child: Container(
        width: 200.0,
        height: 200.0,
        color: Colors.teal,
        child: const Center(
          child: Text('Hello World...!'),
        ),
      ),
    ),
    builder: (BuildContext context, Widget? child) {
      //print('controlValue : $_controller.value');
      return Transform.rotate(
        angle: _controller.value * 2.0 * math.pi,
        child: child,
      );
    },
  ),

- animation (애니메이션컨트롤러 객체) : _controller (아래 전체소스 참조) (필수요소)

- child (자식위젯) : Container() 위젯

- builder (애니메이션 값이 변경될때만다 호출되는 함수) :Transform.rotate() (필수요소)

 

< main.dart >

백번 보는 것보다 한 번 실행해 보는게 중요합니다.

직접 실행해 보기

import 'dart:math' as math;
import 'package:flutter/material.dart';

void main()
{
  runApp(const SampleApp());
}

class SampleApp extends StatelessWidget {
  const SampleApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'AnimatedBuilder Sample App',
      theme: ThemeData(
        primarySwatch: Colors.lightGreen,
      ),
      home: MainScreen(),
    );
  }
}

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

  @override
  State<MainScreen> createState() => _MainScreenState();
}

class _MainScreenState extends State<MainScreen> with TickerProviderStateMixin{

  late final AnimationController _controller = AnimationController(
    duration: const Duration(seconds: 5),
    vsync: this,
  )..repeat();

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('AnimatedBuilder Demo'),
      ),
      //========================================================================
      body: AnimatedBuilder(
        animation: _controller,
        child: Center(
          child: Container(
            width: 200.0,
            height: 200.0,
            color: Colors.teal,
            child: const Center(
              child: Text('Hello World...!'),
            ),
          ),
        ),
        builder: (BuildContext context, Widget? child) {
          //print('controlValue : $_controller.value');
          return Transform.rotate(
            angle: _controller.value * 2.0 * math.pi,
            child: child,
          );
        },
      ),
      //========================================================================
    );
  }
}

 

2. 옵션별 실행 결과

1)

- animation : _controller = AnimationController(duration: const Duration(seconds: 5), ...).repeat()

- builder : Transform.rotate(angle: _controller.value * 2.0 * math.pi, child: child,)

- 실행화면

Animatedbuilder widget

 

2)

- animation : _controller = AnimationController(duration: const Duration(seconds: 1), ...).repeat()

- builder : Transform.rotate(angle: _controller.value * 2.0 * math.pi, child: child,)

- 실행화면

Animatedbuilder widget

 

3)

- animation : _controller = AnimationController(duration: const Duration(seconds: 1), ...).repeat()

- builder : Transform.translate(offset: Offset(_controller.value*700, 0), child: child,)

- 실행화면

Animatedbuilder widget

 

4)

- animation : _controller = AnimationController(duration: const Duration(seconds: 5), ...).repeat()

- builder : Transform.translate(offset: Offset(_controller.value*700, 0), child: child,)

- 실행화면

Animatedbuilder widget

 

5)

- animation : _controller = AnimationController(duration: const Duration(seconds: 5), ...).repeat()

- builder : Transform.scale(scale: _controller.value * 8, child: child,)

- 실행화면

Animatedbuilder widget

 

6)

- animation : _controller = AnimationController(duration: const Duration(seconds: 1), ...).repeat()

- builder : Transform.scale(scale: _controller.value * 8, child: child,)

- 실행화면

Animatedbuilder widget

 

좀 더 자세한 내용은 아래 사이트 참조 바랍니다.

https://api.flutter.dev/flutter/widgets/AnimatedBuilder-class.html

 

AnimatedBuilder class - widgets library - Dart API

A general-purpose widget for building animations. AnimatedBuilder is useful for more complex widgets that wish to include an animation as part of a larger build function. To use AnimatedBuilder, simply construct the widget and pass it a builder function. F

api.flutter.dev

감사합니다.