Flutter: Stateful Widgets vs Stateless Widgets
Flutter is all about widgets. If you want to develop an application you have to first decide which widgets you are going to use. Each widget has its state.
What is State?
The state is information that can read simultaneously when the widget is built and might change during runtime, in short, we can say that the State defines the current properties of the Widget.
Classes that inherit Stateful Widget are immutable, but State is mutable.
(Immutable class means that once an object is created, we cannot change its content. A mutable class is one that can change its internal state after it is created.)
Steps to implement Stateful Widget?
- Create a class that extends ‘StatefulWidget’, that returns state in ‘createState()’
- Create a ‘State’ class for widgets that may change their values during runtime.
- Within the ‘State’ class, implement the ‘build()’ method.
- Call ‘setState()’ function. ‘setState()’ function actually redraws widgets.
Code Sample:
Steps to implement Stateless Widget?
- Create a class that extends ‘StatelessWidget’.
- Create a ‘build()’ method for widgets that never change their values during runtime.
- ‘build()’ method returns widget.
Code Sample:
Full Code and output:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Home(),
);
}
}
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
String name = "";
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text("Stateful Widget Vs. Stateless Widget"),
centerTitle: true,
),
body: Center(
child: Container(
width: 300,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Enter your name',
),
onSubmitted: (String str) {
setState(() {
name = str;
});
},
),
Text("Hello $name!"),
Greet(),
],
),
),
),
),
);
}
}
class Greet extends StatelessWidget {
@override
Widget build(BuildContext context) {
return RaisedButton(
child: Text("Nice to meet you"),
);
}
}
If you want to refer full source code please visit:
👋 Join FAUN today and receive similar stories each week in your inbox! ️ Get your weekly dose of the must-read tech stories, news, and tutorials.
Follow us on Twitter 🐦 and Facebook 👥 and Instagram 📷 and join our Facebook and Linkedin Groups 💬