How to navigate to main page after lottie splash.json completed in flutter?

Issue

How to navigate the main page after the Lottie animation completed in a flutter when I run the code it shows the Lottie animation repeatedly.

Solution

You can copy paste run full code below
You can use AnimationController and in Lottie onLoaded call AnimationController forward().whenComplete then you can do Navigator.push
code snippet

class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
  AnimationController _controller;

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

    _controller = AnimationController(vsync: this);
  }
...  
Lottie.asset(
            'assets/LottieLogo1.json',
            controller: _controller,
            onLoaded: (composition) {
              _controller
                ..duration = composition.duration
                ..forward().whenComplete(() => Navigator.push(
                      context,
                      MaterialPageRoute(builder: (context) => SecondPage()),
                    ));
            },
          ),

To run working demo, you need this file https://github.com/xvrh/lottie-flutter/blob/master/example/assets/LottieLogo1.json
working demo

enter image description here

full code

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
  AnimationController _controller;

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

    _controller = AnimationController(vsync: this);
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView(
        children: [
          Lottie.asset(
            'assets/LottieLogo1.json',
            controller: _controller,
            onLoaded: (composition) {
              _controller
                ..duration = composition.duration
                ..forward().whenComplete(() => Navigator.push(
                      context,
                      MaterialPageRoute(builder: (context) => SecondPage()),
                    ));
            },
          ),
        ],
      ),
    );
  }
}

class SecondPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(body: Center(child: Text("Second Page")));
  }
}

Answered By – chunhunghan

Answer Checked By – Mildred Charles (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *