Stateless vs Stateful Widgets
Stateless widgets and Stateful widgets are the most used widgets in the flutter code.
So before starting you should know what does “Widget” means in flutter.
In Flutter, everything is a widget.
Widgets is UI that you can combine to make a complete app.
Widgets are nested inside of each other to build your app.
Even the root of your app is just a widget.
Coming to Stateless widgets , it is one of the basic type of widget in simple words… if you think anything is there on the screen and not moving or not doing anything at all is Stateless widget.
Suppose you have a button named “Submit” on screen and on click of that button perform no action it’s Stateless widget.
Code snippet to understand Stateless widget :
import 'package:flutter/material.dart';
void main() {
runApp( HelloWorldApp());
}
class HelloWorldApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Stateless Widget App',
home: Scaffold(
appBar: AppBar(
title: Text('Hello World!!'),
),
body: Center(
child: DecoratedBox(
decoration: BoxDecoration(color: Colors.greenAccent),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text('Hello World'),
),
),
),
),
);
}
Stateful widget : if you press any button on screen and on that press any action performed suppose you moved to next screen or any animation apply or any colour change these all shows any action is performed that comes under Stateful widget.
Code snippet to understand Stateful widget :
void _validateForm() {
if (formKey.currentState.validate()) {
formKey.currentState.save();
Navigator.of(context).pop(List());
} else {
if (mounted) {
setState(() {
_autoValidate = true;
});
}
}
}new MaterialButton(
height: 40.0,
minWidth: 80.0,
child: new Text("Login"),
onPressed: () {
_validateForm();
},
So, when Login named text button will be pressed it will move to next screen and validation will be applied on the login screen.
Happy Reading :)