Search code examples
dartflutterstatefulwidget

Understanding the use of StatefulWidget in Flutter


I'm just starting to fiddle with Flutter and I can't understand the point of StatefulWidget. All those widgets do anywhere I've seen in tutorials etc. is instantiate a State<MyWidget> and let it do all the work.
For example, from this (official) tutorial:

class RandomWords extends StatefulWidget {
  @override
  createState() => new RandomWordsState();
}
class RandomWordsState extends State<RandomWords> {
  ...
}

What I want to know is why is it built like that and what is the use of the outer class (in my example RandomWords).

Thanks in advance.


Solution

  • The "outer class" is final, every widget is final (immutable). This means that all its properties have to be final as well:

    class RandomWords extends StatefulWidget {
      final String name;
    
      @override
      createState() => new RandomWordsState();
    }
    
    class RandomWordsState extends State<RandomWords> {
      String name;
    
      @override
      void initState() {
        name = widget.name;
        super.initState();
      }
    
      @override
      Widget build(BuildContext context) => Text(name);
    
      void someMethod() {
        print(widget.name);
        setState(() => name = 'new name');
      }
    }
    

    From the State all fields of the StatefulWidget can be accessed and obviously not changed because they are final.

    State's, however, can change data. setState will execute its callback and then rebuild the State (with the new data).

    StatelessWidget's can also be rebuilt, i.e. when its parent is rebuilding, but all state is lost and no data is kept. That is what State's are being used for.