Flutter load new page in background

Viewed 1358

Scenario: I have a button, when pressed plays an animation and then navigates to a new page. There is a visible wait time to load the new page. This wait time is however quicker than the initial animation. At the moment the user sees the animation play then a visible pause whilst the new page loads.

I was wondering if it is possible to load the new page in the background whilst the animation is playing? This way when the animation has finished there shouldn't be any visible wait time and the user would instantly switch to the new page.

Currently I load the new page using Navigator...

await Navigator.push(thisContext, MaterialPageRoute(builder: (context) {
      return NewPage(
        title: "New Page"
      );
    }));

Was thinking it should be possible to load the new page, then only push it to the navigator when its already loaded and the animation has finished.

This is whats currently happening...

enter image description here

Vs what I want to happen...

enter image description here

2 Answers

Have you tried using the timer, so just set the animated timer to the timer and then navigate later.

Timer(Duration(seconds: animatedSeconds), () {
  // pass your animation time  in seconds and then just navigate 
Navigator.push(thisContext, MaterialPageRoute(builder: (context) {
      return NewPage(
        title: "New Page"
      );
    }));
});

The second page will be created when the page transition begins.

See this official example.

 import 'package:flutter/material.dart';

main() {
  runApp(MaterialApp(
    home: Page1(),
  ));
}

class Page1 extends StatelessWidget {
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Center(
        child: RaisedButton(
          child: Text('Go!'),
          onPressed: () {
            Navigator.of(context).push(_createRoute());
          },
        ),
      ),
    );
  }
}

Route _createRoute() {
  return PageRouteBuilder(
    pageBuilder: (context, animation, secondaryAnimation) => Page2(),
    transitionsBuilder: (context, animation, secondaryAnimation, child) {
      var begin = Offset(0.0, 1.0);
      var end = Offset.zero;
      var curve = Curves.ease;

      var tween = Tween(begin: begin, end: end).chain(CurveTween(curve: curve));

      return SlideTransition(
        position: animation.drive(tween),
        child: child,
      );
    },
  );
}

class Page2 extends StatelessWidget {
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Center(
        child: Text('Page 2'),
      ),
    );
  }
}

Well, so how to init the second page faster?

You have the following options

  1. Fetch the required data before launching the second page and pass them as argument.

  2. You can cache the data when you fetch it for first time, and then onward use the cached data. Also ensure that you invalidate that cached data after a particular time.

Related