Flutter: setState() - A simple manner to update your widget values

 



When displaying data in a Flutter widget, it is common the need for displaying variables values, which maybe have to be a updated based on users actions. For meeting this purpose there are two ways:

a)      a) Update the text value of each GUI element manually, setting the new value element by element.

b)     b) Using a resource as the setState() method, which just after updating the variable value, all references to that on user GUI will be automatically updated.

 Then, how to use setState() method?

First, we need to create the widget state by defining attributes to that:

 class _MyHomePageState extends State<MyHomePage> {

  String name="";
String email="";

In this example the name and email attributes are part of the state of the widget.

Then, when we have to define as the text of our GUI elements the variable (widget state attribute) that it will be binded to. It may be done using the $ char in front of variable name, as in the example below:

 Text(

  '$name',
style: Theme.of(context).textTheme.headline4,
),
Text(
'$email',
style: Theme.of(context).textTheme.headline6,
),

Then, when we update the value of these variables, we have to do that inside inside the setState() method:

void updateState(){
setState(() {
this.name=this.contact.name;
this.email=this.contact.email;
});
You may access the complete source code for this example here:
https://github.com/rafaelqg/code/blob/main/setState.dart

Take a look in a hands-on demonstration about how to use the setState() method:



Comments

Popular posts from this blog

HASHLIB: Using HASH functions MD5 and SHA256

Spread Operator

Dart: implementing Object Oriented Programming (OOP)