In the document of setState() we can find the following:
- Notify the framework that the Internal state of this Object has
changed.
- Calling setState notifies the framework that the Internal
state of this Object has changed in a way that Might Impact the user
interface in this subtree, which causes the framework to Schedule a
build for this State Object.
So we can understand that the setState()
when called, will redraw your widget or better, will call your method build
again, but will not be "listening" to the changes... If there is any other change to the object, to be redesigned again, you need to call the setState()
once again.
Example
In the example below, when calling setState()
, you will be calling again build
, so the data on the screen will be redesigned with the new values set.
class Cliente{
String nome = "";
String sobrenome = "";
}
class CadastroCliente extends StatefulWidget {
const CadastroCliente({ Key key }) : super(key: key);
@override
_CadastroClienteState createState() => _CadastroClienteState();
}
class _CadastroClienteState extends State<CadastroCliente> {
Cliente cliente = Cliente();
String apelido = "";
@override
Widget build(BuildContext context) {
return Column(
children: <Widget> [
Column(
children: <Widget>[
Text(cliente.nome),
Text(cliente.sobrenome),
Text(apelido),
RaisedButton( /* Botão 1 */
child: Icon(Icons.refresh),
onPressed: (){
setState((){
cliente.nome = "Matheus";
});
cliente.sobrenome = "Ribeiro";
apelido = "Matt";
}
),
]
)
]
);
}
}
~~ It’s just an example for understanding, there may be some errors when trying to run :D ~~
I can not say for sure why, but it is advisable you set the values within the
setState((){
cliente.nome = "Matheus";
cliente.sobrenome = "Ribeiro";
apelido = "Matt";
});
for being a synchronous method, it is good to do what you need within yourself.
And yes, all the objects that are in _CadastroClienteState
shall be tested for new values at the time when the build
be called again.
Observing
If you are using the Bloc standard, you will not use the setState()
, of a study on, for it is interesting you use StreamBuilder
within a StatelessWidget
.
Give a read here on documentation to see if your doubts are resolved... If not, then when you have time I leave a more explanatory answer. PS: If you are using the Bloc standard, there is no need to use setState().
– Matheus Ribeiro