본문 바로가기
Development/Flutter

Flutter - 화려한 애니메이션이 앱을 감싸네! Lottie

by du.it.ddu 2023. 1. 15.
반응형

모바일 앱을 더욱 아름답게 만들어주는 것이 애니메이션이다.
화면전환, UI가 보여지고 가려지고, 사이즈 변경 등 많은 부분에 애니메이션을 녹일 수 있다.
그렇지만 아이콘이나 이미지라던가, 화려한 애니메이션은 어려운 부분이 많다.
그래서 주로 Lottie를 사용하곤 한다.
https://lottiefiles.com/what-is-lottie

 

What is a Lottie animation? - LottieFiles

Lottie is a JSON-based animation file format that works on any device and platform. LottieFiles lets you create, edit, test, collaborate on and ship a Lottie animation easily.

lottiefiles.com

Lottie는 에어비앤비에서 개발한 JSON 기반의 애니메이션 오픈소스 라이브러리다.
Lottie는 많은 곳에서 활용하고 있고, 훌륭한 도구다.
Flutter에서 Lottie를 어떻게 사용할 수 있는지 알아보자.


1. lottie 패키지 추가

당연하게도, 패키지를 추가해야한다.
https://pub.dev/packages/lottie

 

lottie | Flutter Package

Render After Effects animations natively on Flutter. This package is a pure Dart implementation of a Lottie player.

pub.dev

아래 커맨드로 프로젝트에 lottie 패키지를 추가하자.
flutter pub add lottie


2. Lottie 파일 준비

Lottie 애니메이션 파일이 필요하다면, 아래 페이지에서 무료로 다운로드 받을 수도 있다.
https://lottiefiles.com/featured

 

Featured animations from our community

Featured collection of Free Lottie Animations created with Bodymovin.

lottiefiles.com

세상에 많은 디자이너들이 애니메이션을 제작해서 올려준다.
맘에 드는 애니메이션 파일을 다운로드 받고 감사한 마음으로 사용하자.

마음에 드는 애니메이션 파일을 다운로드 받았다면,
assets 폴더에 파일을 옮겨주고 pubspec.yaml에 입력해주자.
예를들면 아래와 같다.

...

environment:
  sdk: '>=2.18.0 <3.0.0'

dependencies:
  ...

dev_dependencies:
  ...

flutter:

  assets:
    - assets/lottie/my_animation.json
    - assets/lottie/

파일을 특정해도 되고, 폴더를 특정해도 된다.
이것은 본인의 자유!
Lottie 파일이 많다면 폴더를 특정하는게 편리하겠다.


3. Flutter에서 Lottie 애니메이션 사용하기

Lottie 애니메이션을 사용하는 방법은 크게 두 가지이다.
하나는 assets 폴더에 저장한 로컬 파일을 사용하는 것이고,
하나는 네트워크에 있는 파일을 사용하는 것이다.

먼저, Lottie 애니메이션을 적용할 곳에 lottie 패키지를 import한다.
import 'package:lottie/lottie.dart';

import 'package:flutter/material.dart';
import 'package:lottie/lottie.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: ListView(
          children: [
            // Load a Lottie file from your assets
            Lottie.asset('assets/lottie/my_lottie_animation.json'),

            // Load a Lottie file from a remote url
            Lottie.network(
                'https://my.lottie.com/my_lottie_animation.json'),

            // Load an animation and its images from a zip file
            Lottie.asset('assets/lottie/my_lottie_animation.zip'),
          ],
        ),
      ),
    );
  }
}

사용법은 아주 간단하다.
lottie가 asset에 있는 로컬 파일인지, 네트워크인지에 따라 함수를 다르게 호출해주고, 위치를 넘겨주면 된다.
놀라운 것은 zip 파일도 실행이 가능하다는 것이다.


4. Flutter에서 Lottie 애니메이션 좀 더 활용해보기

Lottie 애니메이션의 크기를 조절하려면?

경우에 따라, Lottie 애니메이션의 크기가 크다거나 작을 때 변경하고 싶을 수도 있다.
그럴땐 간단하게 사이즈를 지정할 수 있다.

Lottie.asset(
  'assets/my_lottie_animation.json',
  width: 200,
  height: 200,
  fit: BoxFit.fill,
)

 

Lottie 애니메이션을 컨트롤하고 싶다면?

Lottie 애니메이션의 Duration과 같은 부분을 조절하는 등의 컨트롤이 필요할 수 있다.
이럴 땐 AnimationController를 지정하여 해결할 수 있다.

class MyApp extends StatefulWidget {
    ...
}

class _MyAppState extends State<MyApp> with TickerProviderStateMixin {
  late final AnimationController _controller;

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

    _controller = AnimationController(vsync: this);
  }

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: ListView(
          children: [
            Lottie.asset(
              'assets/LottieLogo1.json',
              controller: _controller,
              onLoaded: (composition) {
                // Configure the AnimationController with the duration of the
                // Lottie file and start the animation.
                _controller
                  ..duration = composition.duration
                  ..forward();
              },
            ),
          ],
        ),
      ),
    );
  }
}

AnimationController를 Lottie 함수에 지정해주면,
Controller를 통해 Lottie Animation을 컨트롤 할 수 있게 된다.


이 외에도 Lottie에 대한 좀 더 심화된 내용은 있지만, 모두 다루지는 않겠다.
Lottie는 앱에 화려한 애니메이션을 더해 완성도를 높여줄 수 있는 아주 훌륭한 도구다.
그렇기 때문에 현업에서도 많이 활용되고 있다.

앱에 애니메이션 도입을 고민하고 있다면, Lottie 활용을 고민해보는 것이 좋겠다.

반응형