Flutter / Flutter Widgets

Understanding Stateless vs Stateful Widgets

In this tutorial, we will delve into the differences between Stateless and Stateful widgets in Flutter. This knowledge is fundamental to creating dynamic, interactive apps.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Explore the concept of Widgets, the basic building blocks for UI in Flutter.

Understanding Stateless vs Stateful Widgets in Flutter

1. Introduction

Brief Explanation of the Tutorial's Goal

In this tutorial, we will gain a comprehensive understanding of Stateless and Stateful widgets in Flutter. Flutter, a UI toolkit by Google, has these two core concepts that are vital for developing interactive and dynamic applications.

What the User Will Learn

By the end of this tutorial, you will understand:
- The difference between Stateless and Stateful widgets
- When to use Stateless and Stateful widgets
- How to create and use Stateless and Stateful widgets

Prerequisites

Basic knowledge of Dart programming language and a basic understanding of Flutter.

2. Step-by-Step Guide

Stateless Widgets

A Stateless widget is a widget that describes part of the user interface which can depend on configuration information in the widget itself and in the widget’s parent but cannot change over time.

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Text('Hello, World!');
  }
}

Stateful Widgets

A Stateful widget is dynamic. The user can interact with a Stateful widget (by typing into a form, or moving a slider, for example), or it changes over time (perhaps a data feed causes the UI to update).

class Counter extends StatefulWidget {
  @override
  _CounterState createState() => _CounterState();
}

class _CounterState extends State<Counter> {
  int _counter = 0;

  void _increment() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return RaisedButton(
      onPressed: _increment,
      child: Text('Increment $_counter'),
    );
  }
}

3. Code Examples

Example 1: Stateless Widget

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Hello Flutter',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Hello Flutter'),
        ),
        body: Center(
          child: Text('This is a Stateless Widget'),
        ),
      ),
    );
  }
}

Example 2: Stateful Widget

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Hello Flutter',
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int counter = 0;

  void incrementCounter() {
    setState(() {
      counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Hello Flutter'),
      ),
      body: Center(
        child: Text('Button pressed $counter times'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: incrementCounter,
        child: Icon(Icons.add),
      ),
    );
  }
}

4. Summary

In this tutorial, we explored the fundamental differences between Stateless and Stateful widgets in Flutter. We learned when and how to use each type of widget and looked at examples of both.

To continue learning about Flutter, you might want to explore the following topics:
- Understanding Flutter's widget tree
- Managing state in Flutter
- Understanding Flutter's GlobalKey

5. Practice Exercises

Exercise 1:

Create a Stateless widget that displays a 'Hello, World!' message.

Exercise 2:

Create a Stateful widget that has a button. Each time the button is clicked, the number of clicks should be displayed.

Exercise 3:

Create a Stateful widget that shows a list of items. Add a button that, when clicked, adds a new item to the list.

Remember, practice is key to mastering Flutter widgets. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

WHOIS Lookup Tool

Get domain and IP details with WHOIS lookup.

Use tool

QR Code Generator

Generate QR codes for URLs, text, or contact info.

Use tool

Hex to Decimal Converter

Convert between hexadecimal and decimal values.

Use tool

Percentage Calculator

Easily calculate percentages, discounts, and more.

Use tool

PDF to Word Converter

Convert PDF files to editable Word documents.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help