Flutter: Stateless vs Stateful Widgets

Flutter: Stateless vs Stateful Widgets

If you are new to Flutter development this famous concept sort of does your head in, Am I right? Before we dive into the difference between Stateless and Stateful widgets, let’s talk about Widgets.

Widgets are the building blocks of your UI for flutter apps given their current configuration or state.

State simply refers to the condition of a system or the way things are set up.

Stateless Widgets

Stateless widgets are static widgets, that is they do not change. These widgets are immutable. They are useful when the part of the user interface we create doesn't need to be updated. Stateless widgets cannot change their state during runtime, This means that they are unable to redraw widgets on the screen while the app is running.

Examples of Stateless widgets are:

  • Icon
  • Text
  • IconButton.
import 'package:flutter/material.dart';
class Calculator extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
                   backgroundColor: Colors.grey,
      appBar: AppBar(title: Text('CALCULATOR')
),
 ),
    );
  }
}

The code snippet above displays a Calculator class that extends a StatelessWidget, which overrides the build method that takes in a parameter of BuildContext which enables us to locate our widget in the widget hierarchy, allowing us to set up an app Bar with a text widget. Visit StatelessWidgets Class

Tip: The shortcut to implement a stateless widget in an IDE such as Android Studio and VSCode is simply to type 'stlss' and click enter

Stateful Widget

Stateful widgets are mutable widgets, It overrides createState() and returns a state. These types of widgets are useful when the part of the user interface created can change dynamically when interacted with. They can be updated at runtime depending on user action or data change. They store their mutable state in separate State objects. Visit StatefulWidgets Class Examples are:

  • CheckBox
  • RadioButton
  • TextFields
import 'package:flutter/material.dart';
class CalcApp extends StatefulWidget {
  const CalcApp({ Key? key }) : super(key: key);

  @override
  _CalcAppState createState() => _CalcAppState();
}
class _CalcAppState extends State<CalcApp> {
  @override
  Widget build(BuildContext context) {
    return Container(
   );
  }
}

The code snippet highlights a class CalcApp, that overrides the createState() function. This function creates a mutable state for the widget at a location in the widget tree. The _CalcAppState extends the state that manages the changes in the widget. Being a stateful widget, The build method is called as often as changes to the User Interface are made.

Tip: The shortcut to implement a stateful widget in an IDE such as Android Studio and VSCode is simply to type 'stful' and click enter