What are Stateless Widgets in Flutter?

Understanding Stateless widgets in flutter
Understanding Stateless widgets in flutter

What is a Stateless Widget?

According to Flutter’s official website, which is the very first resource for learning about anything Flutter, " a Stateless widget is a widget that describes part of the user interface by building a constellation of other widgets that describe the user interface more concretely".

The above definition is how stateless widgets are defined on the flutter.dev official site.

Understanding Stateless widget in Flutter.

To better understand what a stateless widget is, it is important that you understand what a state is first.

Below is the structure for a stateless widget:

import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container();
}
}
import 'package:flutter/material.dart';
class MyApp extends StatefulWidget {
const MyApp({ Key? key }) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return Container(
);
}
}

How the stateless widget works:

When you are building a mobile application, it is important to understand that there are instances where the state of the mobile application should change and cases where it shouldn’t.

A simple example of a stateless widget is when you work on a calculator app, the layout/structure of the UI doesn’t change, i.e., the columns and rows remain the same. However, when a user inputs a number/figure in the text field, it requires a change in the original state, thus making it a stateful widget and the opposite of a stateless widget.

For example, the kitchen state always tends to change, unlike the museum state, where people can’t move things around.

In a kitchen, you will need to move utensils, spices, foodstuff, and equipment around. But, in a museum, you can’t move/touch things because these things are meant to be at a specific spot/state at all times (except, of course, if the management wants it to be treated otherwise).

So, the interactions people make in a museum can’t change the state of things, except of course if it’s a shifting operationshifting here means stealing or moving things illegally.

Why Stateless Widgets?

When you create stateful widgets, you do it because you don’t want to use up memory in rebuilding everything on the screen.

Stateless widgets are should be used for building parts of User interfaces, especially when the UI doesn’t need to be updated.

In doing so, we reserve resources and thereby optimize for performance.

In summary, the state of a stateless widget is not meant to change. A stateless widget is supposed to manage states/situations that don’t get affected by a user’s input.