Advanced

Advanced

State

A state is the data present in a graphical object at a certain moment

Advanced

State

A state is the data present in a graphical object at a certain moment

In this case, we need an ephemeral, aka local, state. This kind of state represents just a single Widget's data.

Advanced

State: example

class MyWidget extends StatefulWidget {
  //...
  State<MyWidget> createState() => _MyWidget();
}
Advanced

State: example

class _MyWidget extends State<MyWidget>{
  int myState;
  void initState() {
    super.initState();
    myState = 0;
  }
  void myMethod() {
    setState(() { myState = 1; })
  }
}
Advanced
Advanced

Controllers

In flutter, controllers allow to give control to the parent widget over its child's state.

Advanced

Controllers

In flutter, controllers allow to give control to the parent widget over its child's state.

If the state is our data, the controller is what manages it.

Advanced

Controllers: how to use them

Advanced

Controllers: example

class _MyCustomFormState extends State<MyCustomForm> {
  final myController = TextEditingController(text: "some default text");
  @override
  void initState() {
    super.initState();
    myController.addListener(_printLatestValue);
  } 
}
Advanced

Controllers: example

TextField(
  controller: myController,
),
Advanced

Controllers: example

void _printLatestValue() {
  final text = myController.text;
  print('Second text field: $text (${text.characters.length})');
}
Advanced