Home > Mobile >  For Flutter, is it better to wrap only actual changes with setState()?
For Flutter, is it better to wrap only actual changes with setState()?

Time:12-15

Is there a difference between wrapping the entire function and only wrapping the actual changes with setState()?

  1. wrapping the entire function

    setState(() {
       if (switchValueAdd) {
         valueAdd.text = (int.parse(num1)   int.parse(num2)).toString();
       } else {
         valueAdd.text = '';
       }
     });
    
  2. wrapping only actual changes

if (switchValueAdd) {
setState(() {
    valueAdd.text = (int.parse(num1)   int.parse(num2)).toString();
});
} else {
setState(() {
    valueAdd.text = '';
});
}

Is there any difference in terms of performance between the above two code snippets? Any help will be appreciated!

Also, with if-else statements, does 'else' cost as much memory as 'if'? In other words, is 'else' basically the same as 'if' but checking if otherwise is true?

Thank you for your effort and time in advance!

CodePudding user response:

It is not difference. setState called only in one case (from if or else, not from both). But if you will have to write readable code, use first variant because it is more readable. And statements is not a high-performance operation.

You can also simplify thin:

valueAdd.text = switchValueAdd
  ? (int.parse(num1)   int.parse(num2)).toString()
  : valueAdd.text = '';

CodePudding user response:

You can refresh state after executing all code of function so, it will reduce refresh build many times and improve performance of app.

    valueAdd.text = switchValueAdd
        ? (int.parse(num1)   int.parse(num2)).toString()
        : valueAdd.text = '';

        /* All your other code which is need to manage state */

        setState((){}); // call after all code executed of function
  • Related