Load a Route before pushing it via Navigator in flutter?

Viewed 272

I'm currently trying to push a named route in flutter.

Works good so far, but the Asset Image for the background is loaded after the route was pushed via Navigator, which does not look good.

Currently I push the route like this:

  @override
  void initState() {
    super.initState();
    Timer(Duration(seconds: 5), () =>
      Navigator.pushNamed(context, routeToPage2)
    );
  }

Is there any way to load a Page / Route without pushing it in the first place, so everything is build correctly when the route is pushed after the set time?

3 Answers

you can use a routegenerator for your page route and popUntil. This behavior will remove existing pages off the stack and push a single page called home page on. The MaterialPageRoute builds your route that is pushed to the navigator. Load your asset in the scaffold of HomePage. It should not require a delay to render

 Navigator.of(context)
                .popUntil(ModalRoute.withName(RouteGenerator.homePage));


class RouteGenerator {
  static const String homePage = "/home";
  static const String customPage = "/custom";
  RouteGenerator._();
  static Route<dynamic> handleRoute(RouteSettings routeSettings) {
    Widget childWidget;
    switch (routeSettings.name) {
      case homePage:
        {
          childWidget = HomePageWidget(title: 'Home Page');
        }
        break;
      case customPage:
        {
          final args = routeSettings.arguments as CustomView;
          childWidget = CustomPageWidget(args);
        }
        break;
      default:
        throw FormatException("Route Not Found");
    }
    return MaterialPageRoute(builder: (context) => childWidget);
  }
}

I guess the Asset Image gets loaded on routeToPage2? In this case the push happens everytime before the image gets load.

Sorry for being a bit too vague, maybe I should have explained my problem more detailed. So basically I have Page1, which pushes after a Timer finished to Page2.

On Page2, I have an Image-Asset, which loads shortly after Page2 is displayed, which did not look nice. This asset is saved on the device.

I wanted to load Page2 somehow in the background, while Page1 is still being displayed to the user, so the Background-image of Page2 does not pop up after the Page is shown.

But I have found myself a suitable solution on my problem. I use the following code on Page1:


late Image backgroundImage;

  @override
  void initState() {
    super.initState();
    backgroundImage = Image.asset("path to image");
    Timer(Duration(seconds: 5),
        () => Navigator.pushReplacementNamed(context, page2));
  }

  @override
  void didChangeDependencies(){
    super.didChangeDependencies();
    precacheImage(backgroundImage.image, context);
  }


This results in preloading the image while Page1 is shown, so the Background-Image does not pop up after Page2 is displayed to the user.

Related