Stateful and stateless widgets in Flutter.

ussop drinking coffee

What's a Widget?

If you are coming from React background then Widget is similar to Components. In a Widget we write the code which is gonna be rendered on the Screen.

Example:

   class AppBarApp extends StatelessWidget {
	  const AppBarApp({super.key});
	  
	  @override
	  Widget build(BuildContext context) {
	    return const MaterialApp(
		     home: const Text("Hello world"),
	    );
	  }
	}

We use either StatelessWidget or StatefulWidget to create a new widget by extending one of them depending on our use case.

State?

State can be defined as any variable which expects a rerender of the widget on value update.

StatelessWidget

UseCase: A widget that does not require mutable state.

If the widget doesn't require mutable variables whose update will cause a rerender then we can go for the StatelessWidget.

StatelessWidget can contain only final or const type variables

Widgets like:

  1. list of items
  2. Dashboard stuff
  3. Cooking recepies

any widget which will only display data to UI and not expect a rerender after any action performed by the user.

Example:

	class GreenFrog extends StatelessWidget { 			             
	 const GreenFrog({ super.key });
	 
	 @override 
	 Widget build(BuildContext context) {
	  return Container(color: const Color(0xFF2DBD3A));
	   }
	 }

StatefulWidget

UseCase: A widget that has mutable state.

StatefulWidget will cause a rerender of the widget whenever the state is updated using the setState() method.

we need to use the setState method otherwise the state's value will be updated but the widget will not get rerendered, so it will display the old state in UI.

Example:

	class Bird extends StatefulWidget {
	   const Bird({ super.key, this.color = const Color(0xFFFFE306), this.child, });
	   
	   final Color color;
	   final Widget? child;
	   
	   @override State<Bird> createState() => _BirdState(); 
	   } 
	 
	 class _BirdState extends State<Bird> { 
	 double _size = 1.0; 
	 
	 void grow() { 
	   setState(() { _size += 0.1; });
	 } 
 
	 @override 
	 Widget build(BuildContext context) {
	   return Container( color: widget.color, transform: Matrix4.diagonal3Values(_size, _size, 1.0), child: widget.child, ); 
	 } 
	}

In the above widget the UI will get rerendered whenever the value of _size state is updated.

Thanks for reading the article 🎉