Search code examples
flutterflutter-widgetflutter-routes

How to execute a method after current widget has finished loading?


I have a flutter app with 2 widgets/pages namely:
- Loading widget/page (Comes up right on startup of the app)
- Home widget/page

I want to launch the home page after loading page has completed loading. Basically my question is - How can I get to know when my widget has finished loading?

Following is my code:

// My main.dart
import 'package:flutter/material.dart';
import 'package:routes/pages/home.dart';
import 'package:routes/pages/loading.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      routes: {
        '/': (context) => Loading(),
        '/home': (context) => Home(),
      },
    );
  }
}

class Loading extends StatefulWidget {
  @override
  _LoadingState createState() => _LoadingState();
}

class _LoadingState extends State<Loading> {
  @override
  void initState() {
    super.initState();
    // Below line of code causes problem. How can I call to route to new page after current widget has completed loading 
    launchAnotherWidgetAfterDoingSomething();
  }

  void launchAnotherWidgetAfterDoingSomething() {
    // Do some necessary logic....
    Navigator.pushReplacementNamed(context, '/home');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Loading screen'),
      ),
    );
  }
}

Solution

  • You can try this

    @override
    void initState() {
      super.initState();
    
      // ...
      _gotoHome();
    }
    
    // ...
    
    void _gotoHome() {
      Future.delayed(Duration.zero, () {
        Navigator.of(context).pushReplacementNamed('/home')
      });
    }
    

    Edit
    To trigger an actio after every widget is built in your page add this in your initState

    WidgetsBinding.instance.addPostFrameCallback((_) {
      // do what you want here
    });