Flutter performance of StatefulWidget and StatelessWidget - flutter

I use a lot StatelessWidgets when I have to create "templates" of widgets that are used multiple times inside my app because the docs say so:
Stateless widget are useful when the part of the user interface you
are describing does not depend on anything other than the
configuration information in the object itself and the BuildContext in
which the widget is inflated.
Here is an example:
class StepInputButton extends StatelessWidget {
final int pos;
final String value;
const StepInputButton({
this.pos,
this.value
});
#override
Widget build(BuildContext context) {
return Row(
// Text, Icon and a tiny button
);
}
}
The above is good because I can use const StepInputButton(val, "val"), in the code with CONST which improves performances.
PROBLEM
I am using the famous Provider widget to manage the state and the page of my apps usually look like this:
class SuccessPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
var prov = Provider.of<Type>(context);
return Scaffold(...);
}
}
That's a page of my app with Scaffold that has a Drawer, a float action button and an appTitle.
Here I use a StatelessWidget because I do not use setState() since provider does all the work for me. But still in the official flutter doc they say:
For compositions that can change dynamically, e.g. due to having an
internal clock-driven state, or depending on some system state,
consider using StatefulWidget.
So do I have to change class SuccessPage extends StatelessWidget to class SuccessPage extends StatefulWidget? Do I get advantages?
Note: if you want to put the question in another way: should I use StatefulWidgets to create "app pages" whose state is going to change and StatelessWidgets for "reusable widgets" whose state doesn't change?

StatefulWidget is necessary for when the widget itself is maintaining its own state. In the example you gave, the Provider package is handling the state for you, assuming you're using the correct provider type higher up the widget tree (for example, ChangeNotifierProvider). There also doesn't seem to be anything in this code that would benefit from having access to the widget's lifecycle, so you wouldn't need access to methods like initState or dispose.
As such, there's nothing for the widget itself to manage, so converting your class to be stateful is unnecessary.
One thing I might suggest, though, is to use a Consumer instead of calling Provider.of directly. A Consumer handles the call for you and removes any ambiguity on whether your widget will get updated when the Provider detects a state change.

You use StatelessWidget for widgets that don't change their state, that will stay the same all the time. Example, appBar is stateless.. The build(...) function of the StatelessWidget is called only once and no amount of changes in any Variable(s), Value(s) or Event(s) can call it again.
Therefore, when you need to change state(ex value) then use StatefulWidgets, basically StatelessWidget is used for building UI widgets that are static

Keeping it simple:
If you have non-final global variables in your widget then you need a StatefulWidget
If all global variables are final then you should use StatelessWidget;
Reason:
If your global variable is non final that means it is allowed to change and if it's value is changed that means state of your object(Widget) is changed (basic oops concept I am talking about). In such case you would like to call build method of your widget so that your changes get applied on the UI (if it matters for your UI). We do it by calling setState(); and so we use StatefulWidget for such use-case.
If it is enough that once you initialize your global variable in constructor, you don't need to assign it any value in future then in such case use StatelessWidget.
I have tried to keep it very simple and not technical enough so, if you still have any doubts please comment on this answer.

Related

Why does ChangeNotifierProvider exist?

According to Flutter's documentation here (https://flutter.dev/docs/development/data-and-backend/state-mgmt/simple),
one way to control the state management is to use ChangeNotifierProvider(or InheritedWidget) when one of its descendants is a Consumer which is rebuilt when the underlying ChangeNotifier changes.
Flutter's team reiterates that approach on the official youtube Flutter channel.
However, that means that some business logic element (ChangeNotifier) is now part of the Widget tree (which otherwise is all about how the UI will look like). So I don't understand why those classes (ChangeNotifierProvider,InheritedWidget,Consumer) even exist.
In particular, why isn't the following approach superior:
-Business logic is a singleton and a ChangeNotifier.
-Instead of Provider(...), for every Widget depending on the business logic simply do this:
BusinessLogicSingleton.instance.addListener(() {
setState(() {
});
at initState(...).
What am I missing here?
You can indeed do that, but then you'd also have to remember to close the listener on dispose. Providers handle that automatically.
How do you plan to set state in stateless widgets? Also following your suggested method, you would be rebuilding the entire widget with setstate, vs building only a specific part even for complex widgets if you were to use consumers.
I think there are benefits to have the ChangeNotifier a part of the widget tree. You need to ask yourself: what are the features of the Widget Tree that can benefit ChangeNotifier? Or rather - by using Widget Tree, can I get everything I get from Singleton? And can I do some things Singleton does not provide?
First - if you put your ChangeNotifier high in the tree, and you create only one ChangeNotifier for your class (e.g. ChangeNotifier) - you practically have a singleton. With added benefit of a Widget Tree logic taking care of disposing your ChangeNotifier etc.
Second - you can have multiple ChangeNotifiers of the same class in different parts of the tree, practically scoping your ChangeNotifier any way you want. This is not something a Singleton approach can offer. I'm not sure this is a good example - but imagine your ShoppingCart demo: it has a single ShoppingCart ChangeNotifier provider at the top of the tree.
Now imagine one of the items you sell are customizable - like Pizza. And when user selects Pizza - you open additional screen where a user will chose toppings. Now, this additional screen could have a new instance of ShoppingCart - tracking the toppings you added, with all the features of the shopping cart - add, remove etc. This way your module (Pizza toppings selection) becomes self-contained - it does not expect a Singleton to be provided for it, but it will inject it's own ChangeNotifier into the tree.
With the Singleton approach you would need to come up with another way - extending your shopping cart for the sake of creating another Singleton. Not very practical.
Following up on the question, the following hyper-simple class saves me a lot of boilerplate code, and illogical code (forcing ChangeNotifier to be a part of the Widget tree via Provider etc)
import 'package:flutter/material.dart';
//A class which makes it easier to worker with change notifier without provider/consumer which looks wrong since changenotifier shouldn't be forced into widgets tree for no reason
//eg widgets should represent UI and not business logic
class ListenerWidget extends StatefulWidget {
const ListenerWidget({Key? key,required ChangeNotifier notifier,required Widget Function(BuildContext) builder,void Function()? action}) : notifier=notifier,builder=builder,action=action,super(key: key);
final Widget Function(BuildContext) builder;
final ChangeNotifier notifier;
final void Function()? action;
#override
_ListenerWidgetState createState() => _ListenerWidgetState();
}
class _ListenerWidgetState extends State<ListenerWidget> {
void emptyListener(){
setState(() {
});
}
#override
void initState() {
widget.notifier.addListener(widget.action??emptyListener);
super.initState();
}
#override
void dispose() {
widget.notifier.removeListener(widget.action??emptyListener);
super.dispose();
}
#override
Widget build(BuildContext context) {
return widget.builder(context);
}
}

Flutter Widget rebuild after one of the property changed

How to manage to force a Widget to rebuild immediately after one of the property value has changed?
Some pseudo code:
class Live extends StatefulWidget {
String name;
Live(this.name);
#override
_LiveState createState() => _LiveState();
}
class _LiveState extends State<Live> {
// some turbo logic I don't want to move to Live class
..
#override
Widget build(BuildContext context) {
return Column(childrens: [
Text(widget.name),
Card(content calculated based on turbo logic),
]
);
}
}
When String name property has updated (based on parent's setState call), everything is happening in real time. The change is reflected immediately in Text widget. The value is visible immediately only because i am using widget.name call so in built() method I am using property from Live class instead of State.
The problem is that another widget wrapped in Card is calculated in place marked as // some turbo logic I don't want to move to Live class. Due to this fact when I want to see updates in this section I need to switch tab and go to e.g Setting and then return to Live tab to see changes related to Card content. I believe it trigger build() method again.
Golas:
Once the name value is updated in Live widget, a State widget rebuilds immediately.
do not move turbo logic to Live class and keep it in State class
First off, your StatefulWidget should be immutable and therefore only contain immutable fields. I'd suggest you move the name field into State and change it there using a setter. The setter should call setState(), this will cause the desired rebuild.
See this introduction for more information - specifically the "Bird" sample code to see how to code a setter.

Flutter: Is it ok to store dependencies in Widget instance variables outside of the build method?

In my Flutter app I'm using get_it to retrieve non-widget related dependencies (e.g. an http service).
Most of the Flutter Widget examples that I see don't save any variables in the widget class, but rather they retrieve them in the #build method. This makes sense for dependencies that rely on the context, but for other dependencies that don't rely on context is it ok to save them as instance variables when the constructor is called?
I'm not very familiar with the Widget lifecycle so I'm not sure if this could lead to memory leaks, etc if widget instances are discarded. I want to save them as variables because it more clearly documents the dependencies.
Fetching in #build
class MyWidget extends StatelessWidget {
#override
Widget build() {
var myService = GetIt.instance.get<MyService>();
}
}
Storing in instance variable
class MyWidget extends StatelessWidget {
final MyService myService;
MyWidget(): myService = GetIt.instance.get();
#override
Widget build() {
}
}
I see no reason why you couldn't store them as an instance variable.
You obviously cannot dispose of instance variables in a manual/clean way and must rely on the garbage collector to do what it should. That could be seen as a drawback. In your case I assume that isn't an issue since the service might live throughout the lifecycle of the app.
If you are very nervous about memory leaks, use a stateful widget and dispose the things needing disposal.
If you very clearly want to document the dependencies you could go further and require it as a parameter to the widget. It would also make the widget more easily testable.

Problem with understanding this code in flutter

I was learning flutter and came across this code:
class MyStatelessWidget extends StatelessWidget {
final String name;
MyStatelessWidget(this.name);
#override
Widget build(BuildContext context) {
return Text('Hello, $name!');
}
}
Sorry, I would like to ask some questions on the above code. Firstly, why need to use #override, that is,I know it is needed for method overriding but is it true that build method in StatelessWidget is defined like this build(){} therefore we need to override it and add some logic? Secondly, here Widget build Does Widget mean that build returns a Widget? Thirdly, why do we need to use BuildContext here build(BuildContext context)?
CONTEXT
From the docs, BuildContext is:
A handle to the location of a widget in the widget tree.
context is a BuildContext instance which gets passed to the builder of a widget in order to let it know where it is inside the Widget Tree of your app.
One of the common uses is passing it to the of method when using an Inherited Widget.
Calling Something.of(context), for example, returns the Something relative to the closest widget in the tree that can provide you that Something.
BUILD METHOD
Build method is required because it describes the part of the user interface represented by this widget.The framework calls this method in a number of different situations.
Read more about build method here Build Method
STATELESS WIDGET
A widget that does not require mutable state.
A stateless widget is a widget that describes part of the user interface by building a constellation of other widgets that describe the user interface more concretely.
Read more about stateless widget here Stateless widget
I hope this helps.

Flutter: can a StatelessWidget return a StatefulWidget from its build method?

I am wondering what will happen if I define a StatelessWidget but return a stateful Widget from its build method? I've tried it and everything seems to be working, but I just want to know what is going on behind the scene so that I can be sure nothing will break when I ship it into production. Specifically:
1) I am wondering if every rebuild of the parent StatelessWidget will trigger a rebuild of the StatefulWidget it returns? If so, is it saying I am effectively returning a StatelessWidget?
2) I am wondering if the parent StatelessWidget will still be in the widget tree, given it is merely a wrapper and does not have any visual element to be rendered?
3) If I want to give the child StatefulWidget a Key, should I give the parent StatelessWidget the same key? Or, should I just put the key on the parent StatelessWidget?
Mixing Stateless and Stateful is a very, very, very common use-case.
The answer is relatively simple: Nothing special happens.
Stateless+Stateful is the same as Stateless*2 or Stateful*2. There's no behavior change and no extra code needed.
I am wondering if every rebuild of the parent StatelessWidget will trigger a rebuild of the StatefulWidget it returns? If so, is it saying I am effectively returning a StatelessWidget?
No. Each widget is independent and can rebuild without forcing other widgets to rebuild.
A child rebuilding won't make the parent rebuild. Similarly, a parent rebuilding doesn't necessarily force the child to rebuild either.
I am wondering if the parent StatelessWidget will still be in the widget tree, given it is merely a wrapper and does not have any visual element to be rendered?
Yes, a StatelessWidget is still in the tree.
No, it is not "just a wrapper." A StatelessWidget can use InheritedWidgets and override ==.
These can cause the widget to rebuild independently from other widgets. And as such, this widget must say in the tree.
It even has a setState equivalent; it's just not public.
If I want to give the child StatefulWidget a Key, should I give the parent StatelessWidget the same key? Or, should I just put the key on the parent StatelessWidget?
No. That's not needed.
If the key is on a widget, this will impact its entire subtree. So there's no need to put it on descendants too.
In fact, you can't, depending on the Key. GlobalKey, for example, requires to be unique.