Flutter Reusable Lottie Animations技巧

2022-12-10

这篇文章主要为大家介绍了Flutter Reusable Lottie Animations技巧,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

目录
  • 正文
  • 封装相关加载数据使用的lottie动画
    • 测试一下

正文

你是否想要在app里面新增一些炫酷的动画,但是呢?虽然Flutter提供了很多的动画,但是自己绘制吧,要么效果调整上过于耗费时间了,要么效果不尽人意。

专业的事情交给专业的人,如果动画是设计师提供并且能拿来使用,那就太好了!!!

曾经使用过gif,现在发现lottie动画,太香了~

封装相关加载数据使用的lottie动画

下面是我封装的有关加载数据使用的lottie动画

用关键值在枚举中定义动画,每个值都是磁盘上动画文件的名字。

enum LottieAnimation {
    dataNotFound(name: 'data_not_found'),
    empty(name: 'empty'),
    loading(mame: 'loading'),
    error(name: 'error'),
    smallError(name: 'small_error');
    final String name;
    const LottieAnimation({
        required this.name,
    });
}

创建一个基类,所有其他动画类都从该基类派生。这个类完全负责使用磁盘上的assets来呈现lottie动画。

在build方法里面,我们通过Lottie.asset返回一个实际的小部件。

class LottieAnimationView extends StatelessWidget {
    final LottieAnimation animation;
    final bool repeat;
    final bool reverse;
    const LottieAnimationView({
        super.key,
        required this.animation,
        this.repeat = true,
        this.reverse = false,
    });
    @override
    Widget build(BuildContext context) => Lottie.asset(
        animation.fullPath,
        reverse: reverse,
        repeat: repeat,
    );
}

给LottieAnimation增加一个拓展,获取文件全路径

extension GetFullPath on LottieAnimation {
    String get fullPath => 'assets/animationss/$name.json';
}

然后定义子类,只把lottie动画的名字传递给父类,你就可以开始是了!

class EmptyContentsAnimationView extends LottieAnimationView {
    const EmptyContentssAnimationView({super.key}) : super(
        animation: LottieAnimation.empty,
    );
}

测试一下

class HomePage extends StatelessWidget {
    const HomePage({Key? key}) : super(key: key);
    @override
    Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(
                title: const Text('Home Page'),
            ),
            body: const EmptyCOntentsAnimationView(),
        );
    }
}

搞定,接下来我得研究研究 如何制作一个lottie动画了,更多关于Flutter Lottie Animations的资料请关注北冥有鱼其它相关文章!

《Flutter Reusable Lottie Animations技巧.doc》

下载本文的Word格式文档,以方便收藏与打印。