Life Cycle of Flutter Widgets

The widgets contain their life cycle and it is stateless. We want structures to stay the same all over the app. For example, AppBar, Textview, etc. widgets are immutable. Flutter provides a Hot Reload that can reflect changes in the application.


The life cycle of stateless widgets is simple: only one stage of the build method is called automatically while running the application. 

Example:

class MyApp extends StatelessWidget {

const MyApp({super.key});

 

//This method called automatically

@override

Widget build(BuildContext context) {

return null;

}

}

There are methods for the life cycle of flutter widgets.

Init State (): 

The init state gets triggered when the application is run. We want something to happen the moment our stateful widget is created.

Build (): 

The build method is triggered when the widget is constructed and the UI loads on the screen. This method is called every time while running the application. 

Deactivated():

The Deactivate method is called when the stateful widget is destroyed. This method is used for destroying objects and variables.                   

Example of the life cycle: 

class MyHomePage extends StatefulWidget {

const MyHomePage({super.key, required this.title});

final String title;

@override

State<MyHomePage> createState() => _MyHomePageState();

}

class _MyHomePageState extends State<MyHomePage> {

@override

void initState() {

super.initState();

}

@override

void deactivate() {

super.deactivate();

 

}

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(

backgroundColor: Theme.of(context).colorScheme.inversePrimary,

title: Text(widget.title),

),

body: const Center(

child: Column(

mainAxisAlignment: MainAxisAlignment.center,

children: <Widget>[

Text(

'Welcome Flutter',

),],),),);}}

 

Happy Coding!


365Bloggy May 8, 2024
Share this post
Tags
SUBSCRIBE THIS FORM


Archive