DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Angular vs. Flutter for Web App Development: Know Which One Is Best?
  • Cross-Platform App Development: Exploring the Essential Tech Stack for Success
  • Legacy Code Refactoring: Tips, Steps, and Best Practices
  • How to Build a Video Streaming App With Screen Sharing Using Flutter

Trending

  • Java Backend Development in the Era of Kubernetes and Docker
  • Swift Concurrency Part 4: Actors, Executors, and Reentrancy
  • Lease Coordination Under Serializable Isolation in CockroachDB
  • Stop Guessing, Start Seeing: A Five -Layer Framework for Monitoring Distributed Systems
  1. DZone
  2. Coding
  3. Frameworks
  4. Stateless vs. Stateful Widgets: Make the Right Choice for Your Flutter App

Stateless vs. Stateful Widgets: Make the Right Choice for Your Flutter App

Learn about the two types of widgets in Flutter: stateless and stateful. Discover how they differ in handling state when to use each, and how to create them.

By 
Saad Ahsan user avatar
Saad Ahsan
·
Sep. 25, 23 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
4.9K Views

Join the DZone community and get the full member experience.

Join For Free

Flutter has two types of widgets: stateless widgets and stateful widgets. The purpose of this article is to explain what they are, how they differ when they can be used, and how to create them. We will also provide some examples and tips to help you understand and use them effectively in your Flutter apps.

What Are Stateless and Stateful Widgets?

A widget is either stateless or stateful, depending on whether it can change its appearance or behavior in response to events or data changes.

A stateless widget is a widget that does not have any internal state to manage. It does not depend on any external data or user input, and it does not change its appearance or behavior over time. A stateless widget is immutable, meaning that its properties are final and cannot be modified once the widget is created. A stateless widget is also idempotent, meaning that it always returns the same output for the same input.

Stateless widgets include Text, Icon, IconButton, and RaisedButton. These widgets display static content or perform simple actions that do not affect their appearance or behavior.

A stateful widget is a widget that has an internal state to manage. It can depend on external data or user input, and it can change its appearance or behavior over time. A stateful widget is mutable, meaning that its properties can be modified after the widget is created. A stateful widget is also non-idempotent, meaning that it may return different outputs for the same input.

Stateful widgets include Checkboxes, Radios, Sliders, InkWells, Forms, and TextFields. These widgets display dynamic content or perform complex actions that affect their appearance or behavior.

How Do They Differ?

The main difference between stateless and stateful widgets is how they handle their state. The state is the information that can change during the lifetime of a widget, such as a slider’s current value or whether a checkbox is checked.

A stateless widget does not have any state to manage, so it does not need to store or update any information. A stateless widget only needs to implement one class: a subclass of StatelessWidget. This class overrides the build method, which takes a BuildContext as a parameter and returns a Widget as a result. The build method describes how to display the widget on the screen based on its properties and context.

A stateful widget has a state to manage, so it needs to store and update some information. It implements two subclasses: StatefulWidget and State. The StatefulWidget class creates an instance of the State class and associates it with the widget. The State class contains the widget’s mutable state and its build method. The build method describes how to display the widget on the screen based on its properties, context, and state.

State objects call setState() when the widget's state changes, causing the widget to be redrawn. The setState() method takes a function as a parameter, which performs the state update logic. The framework then calls the build method again with the new state, updating the widget’s appearance or behavior.

When To Use Them?

The choice between using a stateless or a stateful widget depends on the functionality and purpose of your widget. 

You should use a stateless widget when:

  • Your widget does not depend on any external data or user input.
  • Your widget does not change its appearance or behavior over time.
  • Your widget only needs to display static content or perform simple actions.
  • Your widget does not need to store or update any information.

You should use a stateful widget when:

  • Your widget depends on external data or user input.
  • Your widget changes its appearance or behavior over time.
  • Your widget needs to display dynamic content or perform complex actions.
  • Your widget needs to store or update some information.

How To Create Them?

To create a stateless widget in Flutter, you need to follow these steps:

  1. Create a class that extends StatelessWidget.
  2. Override the build method that takes a BuildContext as a parameter and returns a Widget as a result.
  3. Use other widgets as children or properties of your widget.
  4. Return your widget from the build method.

For example, this code creates a simple Hello World app using a stateless widget:

Dart
 
import 'package:flutter/material.dart';

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

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


To create a stateful widget in Flutter, you need to follow these steps:

  1. Create a class that extends StatefulWidget.
  2. Create a class that extends State and associates it with the StatefulWidget class using a generic type argument.
  3. Override the build method that takes a BuildContext as a parameter and returns a Widget as a result.
  4. Use other widgets as children or properties of your widget.
  5. Declare any variables that represent the widget’s state and initialize them in the constructor or initState method.
  6. Return your widget from the build method.
  7. Call setState() whenever you need to update the widget’s state and provide a function that performs the state update logic.

For example, this code creates a simple counter app using a stateful widget:

Dart
 
import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  int _counter = 0; // Declare a variable to store the counter value

  void _incrementCounter() { // Define a function to increment the counter value
    setState(() { // Call setState to update the state
      _counter++; // Update the state variable
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Counter App'),
        ),
        body: Center(
          child: Text('You have pushed the button $_counter times'),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: _incrementCounter, // Call the function when the button is pressed
          child: Icon(Icons.add),
        ),
      ),
    );
  }
}


Conclusion

Stateless and Stateful widgets are foundational concepts in Flutter app development. Understanding their characteristics and use cases allows you to make informed decisions when designing your app's user interface. Stateless widgets are ideal for static components that do not require dynamic updates, while Stateful widgets excel in handling user interactions and dynamically changing content.

By leveraging the power of Stateless and Stateful widgets effectively, you can create visually appealing, performant, and responsive Flutter applications that provide a delightful user experience across platforms. Choose wisely, and let the versatility of Flutter's widget system elevate your app development journey.

User experience Virtual screening app Build (game engine) Flutter (software) Framework

Opinions expressed by DZone contributors are their own.

Related

  • Angular vs. Flutter for Web App Development: Know Which One Is Best?
  • Cross-Platform App Development: Exploring the Essential Tech Stack for Success
  • Legacy Code Refactoring: Tips, Steps, and Best Practices
  • How to Build a Video Streaming App With Screen Sharing Using Flutter

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook