How to navigate to a screen that previously built in flutter?

  Kiến thức lập trình

I have a series of APIs that are called on my home page and a series of widgets are created after receiving data from the server.
I want to shorten the loading time of these widgets, so I want my home page to be fully built while my splash screen is being shown, so that when the navigation operation happens, the audience will be faced with a ready page.

tested the following code, but apparently, until the HomeScreen widget is used in the build method, the build operation and calling the apis will not happen on the home page:

import 'package:flutter/material.dart';
import 'package:imam/config/routes/routes.dart';
import 'package:imam/core/utils/extensions.dart';
import 'package:imam/features/home/screens/home_screen.dart';

class SplashScreen extends StatefulWidget {
  const SplashScreen({super.key});

  @override
  State<SplashScreen> createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
  late HomeScreen homeScreen;

  @override
  void initState() {
    homeScreen =  HomeScreen();
    Future.delayed(const Duration(seconds: 3), () {
      context.pushNamed(Routes.homeScreen);
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              'Splash Screen',
              style: TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 24,
              ),
            ),
            SizedBox(height: 20),
            CircularProgressIndicator(),
          ],
        ),
      ),
    );
  }
}

please pay attention that I don’t want to wait for the load data of the home page, I just want all the components of the home page to be created at the same time in those 3 seconds when the splash page is shown.

And I don’t want to use the Stack widget as a trick to solve this problem because the pages are supposed to be moved with navigation.
Thanks for your kindness.

LEAVE A COMMENT