Flutter stateful widget - flutter

class AppWidget extends StatefulWidget {
#override
_AppWidgetState createState() => _AppWidgetState();
}
class _AppWidgetState extends State<AppWidget> {
int _Count = 0;
build(context){}
}
I'm familiar with stateless and stateful widget in flutter but I'm curious why we're not defining stateful widget same as stateless widget? Why we need to declare 2 different class one for createstate method and one for actual state implementation?
I guess may be flutter team use this implementation because when app re-run we can get old state back without losing it if this is the case then How flutter knows?
And if application have more then 1 stateful widget then how flutter manage state for each stateful widget? Again my guess is flutter manage state based on State<AppWidget> but again HOW?

First class is the one that rebuilds the widget if you change anything in it. So for example if you have a text widget in the stateful widget and in the runtime you pressed a button and changed the text from 'Hello World' to 'Hello User' actually what happens is that flutter destroys the second class and rebuild it again with the new text using the first one.
You can find more information in this video from the Flutter Team:
Stateful Widgets Video

Related

How to restart the build method on TabPage in flutter app with auto_route package

Hi a use auto_route package in flutter app. How to restart the build method on TabPage or not save the stack state when switching tabs. I should have an animation run in the build method on TabPage every time I switch a tab in the navigation bar. But the build method is not called when I click the buttons in the navigation bar
I guess you are the same user that commented on my article. I'll give the same answer here. this is not related to the autoroute package itself but it is the default behavior of a bottombar navigation. The objective being to always minimize the number of rebuilds necessary for your UI.
I didn't test it but you could try to make your tab a stateful widget (if it isn't already) and modify this behavior with the AutomaticKeepAliveClientMixin<YourWidget>:
class _YourWidgetState extends State<YourWidget> with AutomaticKeepAliveClientMixin<YourWidget>{
// Here you build your Widget after calling the super method
#override Widget build(BuildContext context) {
super.build(context)
return Container();
}
// the important part is returning false here
#override bool get wantKeepAlive => false;
}

What's a state in flutter?

I just started learning Flutter and as a beginner I'm facing some issues about understanding a state. I watched some videos on YouTube, read articles online. They explain the reason why one should use a Stateful Widget instead of Stateless. But I can't really understand what part of an app needs to be a Stateful Widget and what the use of the setState method is. Also what's the difference between the state of a widget and state of the app?
Flutter is declarative. This means that Flutter builds its user interface to reflect the current state of your app:
State can be described as "whatever data you need in order to rebuild your UI at any moment in time".
When the state of your app changes (for example, the user flips a switch in the settings screen), you change the state, and that triggers a redraw of the user interface.
There is no imperative changing of the UI itself (like widget.setText)—you change the state, and the UI rebuilds from scratch.
The state that you do manage yourself can be separated into two conceptual types: ephemeral(widget state on your question) state and app state.
Ephemeral state
Ephemeral state (sometimes called UI state or local state) is the state you can neatly contain in a single widget.
There is no need to use state management techniques (ScopedModel, Redux, Provider, bloc, etc.) on this kind of state. All you need is a StatefulWidget.
You only need to use setState to alter your current state.
For example, below, you see how the currently selected item in a bottom navigation bar is held in the _index field of the _MyHomepageState class.
In this example, _index is ephemeral state.
class MyHomepage extends StatefulWidget {
const MyHomepage({Key? key}) : super(key: key);
#override
_MyHomepageState createState() => _MyHomepageState();
}
class _MyHomepageState extends State<MyHomepage> {
int _index = 0;
#override
Widget build(BuildContext context) {
return BottomNavigationBar(
currentIndex: _index,
onTap: (newIndex) {
setState(() {
_index = newIndex;
});
},
// ... items ...
);
}
}
Here, using setState() and a field inside the StatefulWidget’s State class is completely natural. No other part of your app needs to access _index.
The variable only changes inside the MyHomepage widget. And, if the user closes and restarts the app, you don’t mind that _index resets to zero.
App state
State that is not ephemeral, that you want to share across many parts of your app, and that you want to keep between user sessions, is what we call application state (sometimes also called shared state).
Examples of application state:
User preferences
Login info
Notifications in a social networking app
The shopping cart in an e-commerce app
Read/unread state of articles in a news app
For managing app state, you’ll want to research your options. Your choice depends on the complexity and nature of your app, your team’s previous experience, and many other aspects.
Here's a link to an example on app wide state management using provider(one of many state management libraries), Example.
Here's a list of libraries that are used for app wide state management, Options.
In summary, there are two conceptual types of state in any Flutter app. Ephemeral state can be implemented using State and setState(), and is often local to a single widget. The rest is your app state.
Both types have their place in any Flutter app, and the split between the two depends on your own preference and the complexity of the app.
In the Stateless widget, the build function is called only once which makes the UI of the screen. It means through that widget you cannot change the UI again. It will render(build) the UI at once. So for those widgets, you need to send the information before building the widget.
Stateful Widgets: The widgets whose state can be altered once they are built are called stateful Widgets. This simply means the state of an app can change multiple times with different sets of variables, inputs, data. Below is the basic structure of a stateful widget. That means you can change the UI of this widget without building it again with help of the setState method.
For more information refer - https://medium.com/flutter-community/flutter-stateful-vs-stateless-db325309deae
if we want to make changes in our UI so that we use statefulWidget
otherwise we use statelessWidget.
in most case we will be using statefulWidget.
that's it.

How do I implement a version of Flutter's WidgetsBindingObserver without using state?

I am building a flutter app and I need to call a method in a provider when the app goes into background.
I can easily do this by creating a Stateful Widget using the WidgetsBindingObserver (like the example here).
Is there a way to do this without needing a Stateful Widget? Provider is a great architecture and state is an anti-pattern.
Possibly, You could try creating a class that isn't a widget and extending WidgetsBindingObserver.
Something like this perhaps
class MyListener extends WidgetsBindingObserver {
MyListener({this.providerInstance}){
WidgetsBinding.instance.addObserver(this);
};
MyProvider providerInstance;
#override
void didChangeAppLifecycleState(AppLifecycleState state) {
providerInstance.doSomethingWithState(state)
}
}
Then implement the listener say in main() or yourApp() where ever your Provider setup is.
Thing is, there really isn't any issue with having a stateful widget at the root of your app somewhere as in the example. I honestly don't think your Anti pattern argument holds any relevance. Its common practice in flutter to have statefull and not statefull widgets.
By not having the statefull widget your just having to keep the state somewhere else, i.e. where ever it is your configuring your providers.

On Flutter, why is the State a Widget itselt?

I'm getting started with flutter and something doesn't make any sense for me.
I understand the need for StatelessWidget and StatefulWidget. In fact, in React we have the exact same concepts. build in Flutter is render in React and StatelessWidget is a React Functional Component whereas a StatefulWidget is a React.Component. So far, so good.
The problem is that, unlike React, on Flutter, the StatefulWidget is not a Widget that happens to have a state. It is actually just a class that has a createState() that creates a state and, now the part that I don't understand, the State<T> class is the actual Widget because State has build 🤯.
For me, it would make much more sense if the StatefulWidget structure would be like:
class MyApp extends StatelessWidget<TState> {
// Here, the state parameter DOES NOT EXIST. This is pseudo-code.
#override
Widget build(BuildContext context, TState state) {
}
}
This way, the build function creates different Elements based on the current state. This would be much more React like.
Why was Flutter implemented this way? Why is the State class actually the Widget and not the StatefulWidget itself?

Why does a stateful widget build itself using a build method in the state class

I'm just learning flutter - I build a few basic tutorials and am now trying to build a simple notepad application.
https://github.com/sketchbuch/examples_flutter/blob/master/notes/lib/src/components/notepad/notepad.dart
In this file I have a stateful widget which has a state property. What I don't understand is why I need the stateful widget at all... the state class seems to be doing everything including building the list of notes.
Am I doing this right? It doesn't seem right that state builds the whole stateful widget...maybe it is just because my app is basic at the moment but the stateful widget doesn't seem to do anything at the moment.
I just would have thought that the staefulwidget would handle rendering and state would just be an object storing properties
As pointless as an empty StatefulWidget subclass looks like, it is necessary. That class is what allows Flutter to manipulate the State subclass.
Without a StatefulWidget, Flutter is unable to create/update/dispose of a State.
StatefulWidget subclass is also a way to customize the behavior of State by adding fields in StatefulWidget and using them in the State class.
You're saying
My Notepad widget as such is not doing anything but my _NotepadState is. Then why should I use the redundant Notepad widget?
Why is it required?
Your Notepad widget is not alone. It has super classes. It extends StatefulWidget which in turn extends Widget (which extends DiagnosticableTree which extends Diagnosticable).
The super classes are doing all the heavy lifting for you and that you had to write almost zero code. Mostly it is used to accept parameters and create state.
Hope that helps!