Call A Function Automatically When App Starts Everytime Using Flutter

admin_img Posted By Bajarangi soft , Posted On 12-10-2020

In flutter the StatefulWidget provides us a method named as initState() which is executed every single time when flutter app’s starts. The initState() method executed every time when a object is inserted into View class tree. This method will class once for each State object is created for example if we have multiple StatefulWidget classes then we can call this method multiple times and if we have single StatefulWidget class then we can call this method single time.

Call A Function Automatically When App Starts Everytime Using Flutter

Call A Function Automatically When App Starts Everytime
Complete Code For Function Automatically When App Starts Everytime In Flutter
Main.dart

import 'package:flutter/material.dart';
import 'dart:io' show Platform;
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
          appBar: AppBar(
            backgroundColor: Colors.amber,
            title: Text("Call a Function Everytime When App Starts"),
          ),
          body: CustomView()
      ),
    );
  }
}

class CustomView extends StatefulWidget {
  CustomViewWidget createState() => CustomViewWidget();
}
class CustomViewWidget extends State {
  @override
  void initState() {
    showAlert(context);
    super.initState();
  }
  Future showAlert(BuildContext context) async {
    await Future.delayed(Duration(seconds: 6));
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: new Text('Welcome To Our App :) .'),
          actions: <Widget>[
            FlatButton(
              child: new Text("OK"),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Center(
          child: Text('Call A Function Automatically When App Starts Everytime',
            style: TextStyle(fontSize: 22,color: Colors.white), textAlign: TextAlign.center,)
      ),
    );
  }

}

 

Related Post