In the "Performance considerations" section of StatefulWidget documentation, third point mentions the following:
If a subtree does not change, cache the widget that represents that subtree and re-use it each time it can be used. To do this, assign a widget to a final state variable and re-use it in the build method. It is massively more efficient for a widget to be re-used than for a new (but identically-configured) widget to be created. Another caching strategy consists in extracting the mutable part of the widget into a StatefulWidget which accepts a child parameter.
Its not clear that what is "state variable" here, and what to to assign, because "build" term is mentioned in that line, and there is also a build method for every widget,
I mean,
Should the user do final Widget widget = MyWidget(); or final Widget widget = MyWidget().build(context);
As they both return Widget,
Also please explain, that is there any difference between the above statements, and what is the use of Builder widget, if we have build method, or do they have different work, if so, then what ???
thanking you
Never, ever ever ever run the build method on your own, the build method is there for flutter to call for itself with an updated context, you should not be using it. Always do MyWidget()
The Builder widget is useful when you need a newer context for something inside your widget, for example:
Widget build(BuildContext context) { // context crated here
return MaterialApp( // navigator created here, after the context was defined
home: ElevatedButton(
onPressed: () => Navigator.of(context).pop()
),
);
}
This code won't work because the context was created before the navigator (which was created along with a material app), you could wrap the button inside a builder widget to get a newer context that already has a navigator
Of course, calling the build method on your own is not good because you won't be passing the correct context to the widget, instead, let flutter handle the context creating and just use normal constructors.
Related
I'm looking into how to write my own widgets. I've seen a number of examples that have a CustomWidget that either inherits from StatefulWidget or StatelessWidget. Is it possible to inherit from Stack or TextBox or one of the widgets that I've seen returned from build? What I'm thinking of is taking a widget like TextBox, adding custom theming, and then exporting it as a new widget to use.
I've seen a lot of examples using Material UI. For my needs, I need something less cookie-cutter that let's me deside what things are meant to look like how they should style.
Thanks.
Yes, you can create a widget extending some other widget but you will probably need to conform to its super constructor.
You are talking about TextBox in your question but it is not a widget so I'm guessing that you were talking about the Text widget or a similar one. Here's a code sample of how you could create your own widget :
class MyText extends Text {
const MyText() : super("my-text"); // Need to pass a data value to the super constructor.
/// You can override the base build method to return a different widget,
/// in this case I am returning the base super.build (which will render
/// the Text widget) wrapped inside a red Container.
#override
Widget build(BuildContext context) {
return Container(
color: Colors.red,
child: super.build(context),
);
}
}
Try the full test code on DartPad
What I'm thinking of is taking a widget like TextBox, adding custom theming, and then exporting it as a new widget to use.
Then, creating a new custom widget by extending TextBox in not the way to go.
If you do that, you will have to hardcode every properties of the constructor of TextBox in yours. It will be a pain to do and to maintain.
FLutter base principle in Composition over Inheritance.
So, in order to achieve what you need (Theming), you just have to use Theme capabilities :
// global theming once and for all for all the app
MaterialApp(
theme: ThemeData(inputDecorationTheme: InputDecorationTheme()),
home: const MyHomePage(),
);
or
// located theme overload just for here
Theme(data: Theme.of(context).copyWith(inputDecorationTheme: InputDecorationTheme()), child: TextFormField());
Theming only may be not enough but you really should avoid inheriting complex native widgets, prefer composition of property factorisation
So i am writing a Flutter application that utilize the MVVM architecture. I have a viewModel for every screen(widget) with ValueNotifiers and i want to initiate the viewModel for that view.
Now most guides suggest a Provider approach, but why provide it when i can just normally initiate it.
Code:
class FooModel{
final ValueNotifier<bool> _active = ValueNotifier<bool>(false);
ValueNotifier<bool> get active => _active;
FooModel(){_active = false;}
doSomething(){_active=!_active}
}
What i want to do:
#override
Widget build(BuildContext context) {
_viewModel = FooModel();
return Scaffold(
body:ValueListenableBuilder<bool>(
valueListenable: _viewModel.active,
builder : (context,value,_){
if(value)return(Text("active");
return Text("unactive");
}
)
}
what is suggested:
Widget build(BuildContext context) {
return Provider<FooModel>(
create: (_) => FooModel(),
builder: (context, child) {
final vm = Provider.of<FooModel>(context);
return ValueListenableBuilder<bool>(
valueListenable: vm.active,
builder: (context, value) {
if (value) return Text("active");
return Text("unactive");
});
},
);
}
Now i understand that what i suggested creates the viewModel with every build, but that should only happen when screen is loaded thanks to ValueNotifier so its fine.
I guess i just don't understand the value of providing the viewModel.
Flutter has a different ideology.
yes, you can create Value Notifier and it's fine to do that but just thinking of the bigger picture.
Check this flow you want to call an API then perform parsing and filtering on that and you have 2 views on the screen to show the same data one is to showcase the data and the other one is to interact with data and this update needs to be reflected on showcased data.
to do this what we need to do?
create valuenotifier at class level that encloses both screen widgets.
Call API and filter code at the class level.
pass this valuenotifier to both screen widgets you may ask why right? well because one class need to update other class widgets. and that's only one way to push updates to the valuenotifier is the object itself. so you will need to pass this valuenotifier in both classes.
once you do that and update has been synchronized if any setState has been called to the main widget that encloses both of this widgets then you need to do all this again.
also there will be multiple instances of valuenotifier which is bad as valuenotifier is a stream and you need to close your streams once you're done with the stream so you will be needing logic to close your streams at any setState event on main widget.
What is provider exactly? and how it works? well, the provider is a change notifier class which calls setState when you call notifyDataChanged or notify method. this triggers the widget state change which is listening to that data changes.
and that widget gets rebuild. This is the same logic for each and every state management library out there Bloc, ScopedBloc, or any widget like streamBuilder or ValueListenableBuilder.
In Flutter if you want to change data you just need to call setState. Just to be testable, more readable and maintainable what we will be doing is to separate logic into different files just like we do in Android or iOS and that's where this type of libraries comes into the picture to reduce our headache of typing code all over again and focusing on the main task which is the functionality of the app.
See we can create loops in different formats
for(int i=0;i<length;i++)
while(i++<length)
for(i in 0...length)
It's up to us to provide clean and understandable code so that any other developer does not need to delete all code just because he isn't able to understand our code.
There's nothing right and wrong here in development. It's matter of what is more convenient or what makes more sense. like int i does not make sense but if we replace it with index or listIndex it will.
Also, one thing to mention is what you're doing is creating a model that is kind of the same as bloc pattern. so you're already halfway through. you just need to call state change from model check bloc and other patterns you will understand.
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.
Considering below class. Is it possible to listen for whenever appStateModel.bar changes? I have a scenario where I want to perform an animation every time a certain value changes, but I can't seem to figure out how to achieve that.
class Foo extends StatelessWidget {
const Foo();
#override
Widget build(BuildContext context) {
var appStateModel = Provider.of<AppStateModel>(context);
return Container(
child: Text('${appStateModel.bar}'),
);
}
}
In your change notifier, you should include notifyListeners() as stated.
With that, it should work.
On the other hand, you can use the build method to act on change events because the widget will rebuild every time notifyListeners() is called (At least at my point of understanding).
If that won't work, there is the Consumer Widget, it consumes a notifier and rebuilds only if notifyListeners() is called.
This widget also provides a child parameter with which you can save performance when using it because it does not need to rebuild when the notifier changes.
I hope this resolves your issue.
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.