In Flutter does avoiding setState() achieve anything? - flutter

In Flutter does avoiding setState() achieve anything?
I have a StatefulWidget (screen) where I use Widgets that handle their own state completely with the exception of the FAB button. The Fab button is disabled or enabled when data has changed in order to allow the update of the DB when data has changed. I posted a question on SO as to how to use Provider to handle that and thus prevent the need to setState(), and implemented that with Provider.
When looking at another screen to implement something similar, I wondered if another solution may be better. This screen also contains Widgets that all handle their own state - TextFields with TextEditControllers, so the only place I was calling setState() was to enable or disable the FAB. I had previously created a Stateful Widget to create a CheckBox with its own state because the standard CheckBox doesn't have state. It's fairly simple and only 50 lines of code. So, I did the same with the FAB, I created a Stateful Widget (CustomFab) that encapsulates a FAB. When it needs to be enabled or disabled, it is called to set its own state, and returns a FAB that is either enabled or disabled with the appropriate color. Because I have other similar screens, I can use that same component with them.
Does it achieve anything by avoiding setState() in this situation (for mobile and Web), and if so, which is the best way to handle that (Custom-Widget or Provider or another)?

setState is merely avoided in Flutter development for two main reasons:
It rebuilds the whole widget, which may hinder performance on consecutive calls if not used correctly.
using setState only as a state management couples the business logic to the UI, which may reduce code re-usability and maintainability.
In simple apps, there are no significant issues in using setState. However, if you need more control over your code, I suggest going for more complex state management patterns.

Related

Why use BloC or Provider in Flutter when we already have Flutter's built-in setState?

Maybe I don't understand the purpose of BloC or Provider but I'm confused as to why we would ever want to use them instead of using Flutter's built-in state management using the Stateful widget. I've just finished an app and can't remember a point where I wished I needed something more than the defaults. Can anyone clear things up for me?
There are a few reasons to use a BloC or Provider rather than Flutter's built-in setState:
BloC and Provider offer a more robust way to manage state.
BloC and Provider make it easier to update state across multiple widgets.
BloC and Provider can be used to manage async data.
BloC and Provider offer a more modular way to structure your code.
There are some case that you need BLoC to make you easier to define each state or condition that happening inside the application.
We will start discussing creating app like https://www.tokopedia.com/ (inspect element and go with phone size preview). You will see that between widget section tokopedia_ss there are some loading animations, and when the data load complete the widget loading animation changed to viewable widget (as user).
in bloc, you will make stateLoading(), stateComplete(data), stateFailed(data). and in the controller or screen you can describe what will happen when bloc state is stateLoading etc...
Creating this case with setstate is more complicated and make your code messy, also setstate will make phone render all the Build() code. not like BloC builder, you can define each widget or section.
So, when there are 10 sections, using Bloc you able to make it render each state but when using standard setstate it will render all the 10 sections in one time every state changes.
More information about BloC: article_about_BloC

Does MVVM require to remove all logic from the Widgets?

I'm having confusion regarding the correct implementation of MVVM architecture in a flutter.
Does MVVM require separating just the UI calls from the UI or
separating the complete logic of the widgets, even if it is to update
a CheckBox?
If using setState does not raise performance issues, should we use it when following MVVM architecture?
If it is okay to have some logic inside of widgets, to what extent
should we do that?
Yes obviously , I suggest you to study Clean Architecture, Basically concept is that, You have to create ViewModel for every screen.
Screen will contain all the Widgets (View)
View Model will contain all functionality and variable which will be hold value which used in Screen (View)
It is perfectly okay for the widget to manage its state internally. It wouldn't make sense e.g. ListView not to manage its scrolling state. The same obviously applies to custom widgets.
See Differentiate between ephemeral state and app state for more information.

What is the best practice to improve performance?

I'm newly learning and creating simple app using flutter.
I created drawer inside Scaffold for some pages and I got confused if when I click the ListTiles, should it be routing the pages or just switch the body widget using setState().
I guess setState() must perform better but I'm not sure if this is a good practice for pages. If it does not have a big difference in performance, I would like to use routing the pages since it will be uniformed.
Personal opinion:
Avoid separating widgets into functions, use StatelessWidget instead. Cause every render function will rebuild whatever parameter changes.
Avoid using setState as much as possible, especially for large Widgets, instead use provider, get or simply use ValueNotifier if you dont want library. Cause setState will mark all things to be rerender include widgets that not need to be rerender.
Do not render too many things at once, if possible only render the views that are / are about to be displayed. Example using ListView.builder instead of ListView, ... etc
With image, please resize to suit your needs, a 2000x2000 image loaded as a 24x24 icon is clearly not a good idea.
using const.
I'd suggest to redirect user to the next page as it won't require a StatefulWidget (you can use navigator to navigate user to another activity) which will be lighter to run, as if you use IndexedStack or dynamically assign the widget it'll require the StatefulWidget..

Should screens be Stateless or Stateful?

I'm developing an app with lots of screens and pages. I've read somewhere that you should use Stateless Widgets whenever you can.
Why is that?
If I have a lot of screens, should those be stateless? And then the content inside be Stateful? Is it better to have both the screen and widgets inside being Stateful?
You should ask yourself some questions about the screen/page to decide if it will be Stateless or Stateful.
The most obvious, does it need to change state?
Do you need to call initState, didChangeDependencies or another lifecycle method?
Is a bad practice to make Stateful when not needed. A good idea might be to start always as Stateless widget and if needed you can change it to Stateful easily with Alt + Enter shortcut (Android Studio).
I always start by creating a Stateless Widget and work with it until I have to change something state. So I could quickly use `Alt-Enter/ Convert to a Statefull from Intellij/AS to change it to stateful. (doing the inverse is not so easy, so...).
Moreover, if you use Stateful widget with some async mechanism, like streams, you could build the widget once and use the streams to update the information you need, and it will not impact the performance of your app so much. But if you call setState many times, this can degrade your App, since for every setState the Widget tree will be rebuilt.
This article from the flutter docs shows interesting tips about handling state change in flutter apps:

Tracking screen views in Flutter with Firebase Analytics

What is the best location for manually logging a screen view in Flutter with an analytics package (in my case I am using Firebase Analytics, eg. track screens)?
Looking at the Flutter lifecycle, it's not clear where it makes sense to track a screen view.
For a StatelessWidget, I think build() might make sense as I guess it's only called one time per screen view.
What about for a StatefulWidget though? In this case build() would not be useful as it could be called many times. Other candidates are initState(), createState() or the constructor which all appear to only be called once although I'm guessing they may all be called more than once per screen view as widgets up the hierarchy are re-built.
The answer is: it depends. For a StatelessWidget, it might be suitable to have an Analytics event in build(), but only if the parent widgets are not re-built frequently. For a StatefulWidget the same applies but you also have to factor in re-builds due to state change (which are, more than likely often).
Really, the safest path is not to call Analytics events in any parts of the widget lifecycle, but instead on the UI event that might trigger a screen, for example, an edit button that opens up an edit screen. However, the problem with that approach is that the screen might be opened from a variety of locations within the app (meaning you have to duplicate Analytics calls across all those locations).
This means the best option is probably to tie Analytics to PageRoute transitions so that it is called consistently whenever a page route is executed. This is demonstrated in the docs. This will miss tracking screens within a tab bar and other types of UI navigation but as the docs also say, one way to handle this is to implement RouteAware and subscribing it to FirebaseAnalyticsObserver (example tabs implementation).