Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Flutter StatelessWidget vs StatefulWidget in depth

Flutter StatelessWidget vs StatefulWidget in depth

Understanding the difference between StatelessWidget and StatefulWidget is fundamental to Flutter development.

This section takes an in-depth look at the use cases and internal working mechanisms of these two types of Widget.


Core difference

There are two main types of Widget in Flutter, and their fundamental difference is whether they can hold mutable state.

Feature StatelessWidget StatefulWidget
State Immutable (immutable) Mutable (mutable)
Rebuild timing Only when the parent Widget rebuilds When state changes + when the parent Widget rebuilds
Performance Higher (no need to listen to state) Slightly lower (requires state management)
Use Cases Static content Dynamic interactive content

StatelessWidget in detail

StatelessWidget is suitable for content that does not change over time. Once created, all its properties are final and cannot be modified.

Use Cases

Example: complete StatelessWidget example

import

'package:flutter/material.dart'

;

// User info display component (stateless)

class

UserCard

extends

StatelessWidget

{

 

// Properties defined as final to ensure immutability

 

final

String name

;

 

final

String email

;

 

final

String avatarUrl

;

 

// const constructor improves performance

 

const

UserCard

(

{

   

super

.

key

,

    required

this

.

name

,

    required

this

.

email

,

   

this

.

avatarUrl

=

''

,

 

}

)

;

  @override

  Widget build

(

BuildContext context

)

{

   

return

Card

(

      child

:

Padding

(

        padding

:

const

EdgeInsets.

all

(

16.0

)

,

        child

:

Row

(

          children

:

[

           

// Avatar

            CircleAvatar

(

              backgroundImage

:

avatarUrl.

isNotEmpty

                 

?

NetworkImage

(

avatarUrl

)

                 

:

null

,

              child

:

avatarUrl.

isEmpty

                 

?

const

Icon

(

Icons.

person

)

                 

:

null

,

           

)

,

           

const

SizedBox

(

width

:

16

)

,

           

// User info

            Expanded

(

              child

:

Column

(

                crossAxisAlignment

:

CrossAxisAlignment.

start

,

                children

:

[

                  Text

(

                    name

,

                    style

:

const

TextStyle

(

                      fontSize

:

18

,

                      fontWeight

:

FontWeight.

bold

,

                   

)

,

                 

)

,

                 

const

SizedBox

(

height

:

4

)

,

                  Text

(

                    email

,

                    style

:

TextStyle

(

                      color

:

Colors.

grey

[

600

]

,

                   

)

,

                 

)

,

               

]

,

             

)

,

           

)

,

         

]

,

       

)

,

     

)

,

   

)

;

 

}

}


StatefulWidget in detail

StatefulWidget is suitable for scenarios that need to respond to user interaction or data changes. It consists of two parts: the Widget itself (immutable) and the State object (mutable).

Use Cases

State object lifecycle

Method Description
initState Called when the Widget is first created, used to initialize state
didChangeDependencies Called when the Widget's dependencies change
build Builds the UI, called on every state change
didUpdateWidget Called when the parent Widget rebuilds
dispose Called when the Widget is removed, used to clean up resources

Example: complete StatefulWidget example

import

'package:flutter/material.dart'

;

// Counter app

class

CounterApp

extends

StatefulWidget

{

 

const

CounterApp

(

{

super

.

key

}

)

;

  @override

  State

<

CounterApp

createState

(

)

=>

_CounterAppState

(

)

;

}

class

_CounterAppState

extends

State

<

CounterApp

{

// Counter state

 

int

_counter

=

0

;

 

// Timer (used to demonstrate dispose)

  Timer

?

_timer

;

 

// 1. initState - initialize state

  @override

 

void

initState

(

)

{

   

super

.

initState

(

)

;

   

// Initialize the counter

    _counter

=

0

;

   

// Start a timer (increments once per second)

    _timer

=

Timer.

periodic

(

const

Duration

(

seconds

:

1

)

,

(

timer

)

{

      _increment

(

)

;

   

}

)

;

 

}

 

// 2. didChangeDependencies - called when dependencies change

  @override

 

void

didChangeDependencies

(

)

{

   

super

.

didChangeDependencies

(

)

;

 

}

 

// 3. build - build the UI

  @override

  Widget build

(

BuildContext context

)

{

   

return

Scaffold

(

      appBar

:

AppBar

(

        title

:

const

Text

(

'Counter'

)

,

     

)

,

      body

:

Center

(

        child

:

Column

(

          mainAxisAlignment

:

MainAxisAlignment.

center

,

          children

:

[

           

const

Text

(

             

'Current count:'

,

              style

:

TextStyle

(

fontSize

:

20

)

,

           

)

,

            Text

(

             

'$_counter'

,

              style

:

const

TextStyle

(

                fontSize

:

48

,

                fontWeight

:

FontWeight.

bold

,

             

)

,

           

)

,

         

]

,

       

)

,

     

)

,

     

// Increment button

      floatingActionButton

:

FloatingActionButton

(

        onPressed

:

_increment

,

        child

:

const

Icon

(

Icons.

add

)

,

     

)

,

   

)

;

 

}

 

// Method to increment the counter

 

void

_increment

(

)

{

   

// Must call setState to trigger a UI update

    setState

(

(

)

{

      _counter

++

;

   

}

)

;

 

}

 

// 4. didUpdateWidget - called when the parent Widget rebuilds

  @override

 

void

didUpdateWidget

(

CounterApp oldWidget

)

{

   

super

.

didUpdateWidget

(

oldWidget

)

;

 

}

 

// 5. dispose - clean up resources

  @override

 

void

dispose

(

)

{

   

// Cancel the timer to prevent memory leaks

    _timer

?

.

cancel

(

)

;

   

super

.

dispose

(

)

;

 

}

}


Correct use of setState

In a StatefulWidget, you must use setState to notify Flutter that the state has changed.

Correct usage

Example: correct setState usage

// Correct: update state inside setState

void

_increment

(

)

{

  setState

(

(

)

{

    _counter

++

;

 

}

)

;

}

// Correct: setState can be omitted when the state update is unrelated to the UI

void

_someInternalLogic

(

)

{

 

// Internal logic that does not affect the UI

  _calculateSomething

(

)

;

}

// Correct: update state after an async operation

Future

<

void

_loadData

(

)

async

{

final

data

=

await fetchData

(

)

;

  setState

(

(

)

{

    _items

=

data

;

 

}

)

;

}

Incorrect usage

Example: incorrect setState usage

// Incorrect: modify state without calling setState

void

_increment

(

)

{

  _counter

++

;

 

// The state has changed, but the UI will not update!

}

// Incorrect: call setState inside the build method

@override

Widget build

(

BuildContext context

)

{

 

// Never call setState inside build!

  setState

(

(

)

{

    _counter

++

;

 

// This causes an infinite loop

 

}

)

;

 

return

Text

(

'$_counter'

)

;

}

setState triggers a re-call of the build method on the next frame draw.

Calling setState frequently or calling setState inside the build method can both cause performance issues.


How to choose

During development, you should choose the appropriate Widget type based on actual needs:

Choose StatelessWidget when

Choose StatefulWidget when