Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'),
      ),
    );
  }
}
like image 203
TheWaterProgrammer Avatar asked Oct 19 '25 14:10

TheWaterProgrammer


1 Answers

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
});
like image 91
dm_tr Avatar answered Oct 22 '25 04:10

dm_tr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!