How to await async initialisation code in initState() [duplicate] - flutter

This question already has answers here:
What is a Future and how do I use it?
(6 answers)
Closed 1 year ago.
I have some code I need to run in my initState() method as it initialises a late variable widgets in the build method depend on. The problem is the method I want to run is asynchronous as I am loading data from the disk using the Shared Preferences package. I tried making the method asynchronous but I get an error in my IDE saying that the initState() method can't be asynchronous. I tried looking up solutions and they said that you can run them without awaiting in the initState() method. I tried this but the problem is that it doesn't await the initialisation so I get the red error screen saying the variable hasn't been initialised. I originally was going to run this in a constructor of a custom class I had that deals with the data but I also get an error saying that the constructor method can' t be async.
My IDE suggested using the didChangeDependencies() as it can be async, however, the build method doesn't await it.
I tried all the answers in this question (Is there a way to load async data on InitState method?) that didn't suggest a StreamBuilder as I am not trying to load a stream that has to do with Authentication. I also tried to change around the order calling super.initState(); before and after the code, etc. and it didn't work.

make a function that is async and perform your asynchronous work in it ..
then call it in initState without async await keywords but like this
#override
void initState() {
checkLoggedIn().then((user) {
// do anything with your data here
});
super.initState();
}

Related

What is init state in flutter?

I have seen in various files about init method under some classes, why we use this method and please also describe other useful methods if you know, Thanks
I have initialized this method but it didn't work properly.
To understand the methods and structure of flutter widgets, you need to understand the lifecycle of flutter screen or flutter application.
So, basically flutter's stateful widgets have really good methods which are
CreateState()
initState()
didChangeDependencies()
build()
deactivate()
dispose()
You can learn more about this on medium
The #initState method is called by Flutter when a widget is inserted into the tree. It's important to note that the initState method is only called once, when the widget is inserted into the tree, and not every time the widget is updated. If you need to perform an operation every time the widget is updated, you can use the didUpdateWidget method instead.
dispose, build, setState, build and much more method are interesting in Flutter, you can try to understand what each method do in this amazing "cookbook" in flutter documentation.
https://docs.flutter.dev/cookbook

Cancel instances of dart.async.StreamSubscription

When I use "StreamSubscription" to instance a value.
StreamSubscription? _webViewListener;
It always show the problem
Cancel instances of dart.async.StreamSubscription.
I promise that there has dispose function.
#override
void dispose() {
_webViewListener!.cancel();
_webViewListener = null;
topController!.dispose();
super.dispose();
}
I have seen the offical methods. However, it does not work for me.
At last, I want to know the function of StreamSubscription. And how to solve this problem.
The most important feature of StreamSubscription is the ability to dispose it. If you don't do this, even though you don't need the subscription anymore, e.g. after leaving a page in Flutter, the stream or the subscription will run forever until the whole program is closed.
If you dispose all subscriptions in the dispose function of your state, you should be able to ignore this warning. Sometimes such warnings are displayed incorrectly.

Flutter - What are the cons of using setState() many times in the app?

Does anyone can explain me what are the consequences, cons, of using setState() a lot of times in the app?
I know that every time I call setState() the screen is rebuilded, but those widget that was already built, will they still be in the memory? how does it work?
Using setState isn't good when talking about performance?
Generally it is recommended that the setState method only be used to
wrap the actual changes to the state, not any computation that might
be associated with the change. For example, here a value used by the
build function is incremented, and then the change is written to disk,
but only the increment is wrapped in the setState:
Future<void> _incrementCounter() async {
setState(() {
_counter++;
});
Directory directory = await getApplicationDocumentsDirectory();
final String dirName = directory.path;
await File('$dir/counter.txt').writeAsString('$_counter');
}
in Flutter it’s okay to rebuild parts of your UI from scratch instead of modifying it. Flutter is fast enough to do that, even on every frame if needed.
Flutter is declarative. This means that Flutter builds its user interface to reflect the current state of your app.
“The rule of thumb is: Do whatever is less awkward.”
from flutter docs

flutter display message on mount [duplicate]

This question already has answers here:
Flutter: Run method on Widget build complete
(14 answers)
Closed 3 years ago.
Beginner question:
I'm trying to display a message as soon as the page display, I can do it with a simple custom message, but I couldn't find any standard way to do it, all search I did leads me to Snackbar or Flushbar, the problem with this 2 is that u can only show it after the build is called, e.g. on onPress, which leads me to the actual question:
How do I get a call back for onMount event, e.g. something like jQuery ready method, that is triggered once the page is mounted (i.e. ready), so that I can call Snackbar for example?
Duplicate to Flutter: Run method on Widget build complete
answer:
#override
void initState() {
super.initState();
if (SchedulerBinding.instance.schedulerPhase ==
SchedulerPhase.persistentCallbacks) {
SchedulerBinding.instance.addPostFrameCallback((_) {
showInFlushbar("Some text");
});
}
;
}

What is initState and super.initState in flutter?

In the documentation it is written but I am not able to understand it.
Called when this object is inserted into the tree.
The framework will call this method exactly once for each State object it creates.
Override this method to perform initialization that depends on the location at which this object was inserted into the tree (i.e., context) or on the widget used to configure this object (i.e., widget).
If a State's build method depends on an object that can itself change state, for example a ChangeNotifier or Stream, or some other object to which one can subscribe to receive notifications, then the State should subscribe to that object during initState, unsubscribe from the old object and subscribe to the new object when it changes in didUpdateWidget, and then unsubscribe from the object in dispose.
You cannot use BuildContext.inheritFromWidgetOfExactType from this method. However, didChangeDependencies will be called immediately following this method, and BuildContext.inheritFromWidgetOfExactType can be used there.
If you override this, make sure your method starts with a call to super.initState().
But I'm not sure about its meaning. Can you explain it?
Credit to #Remi, initState() is a method which is called once when the stateful widget is inserted in the widget tree.
We generally override this method if we need to do some sort of initialisation work like registering a listener because, unlike build(), this method is called once.
And to unregister your listener (or doing some post work), you override dispose()method.
From here
A subclass of State can override initState to do work that needs to happen just once. For example, override initState to configure animations or to subscribe to platform services. Implementations of initState are required to start by calling super.initState
When a state object is no longer needed, the framework calls dispose() on the state object. Override the dispose function to do cleanup work. For example, override dispose to cancel timers or to unsubscribe from platform services. Implementations of dispose typically end by calling super.dispose
Uses of initState()
initState() is a method of class State and it is considered as an important lifecycle method in Flutter. initState() is called only Once and we use it for one time initializations.
Example :
To initialize data that depends on the specific BuildContext.
To initialize data that needs to executed before build().
Subscribe to Streams.
Thank you for the answers, but I will also reiterate what the guys above have state
#overrride
initState() { // this is called when the class is initialized or called for the first time
super.initState(); // this is the material super constructor for init state to link your instance initState to the global initState context
}
Please allow me to quote the content written by others. I think his explanation is excellent.
https://www.geeksforgeeks.org/flutter-initstate/
There are two types of widgets provided in Flutter.
The Stateless Widget
The Stateful Widget
As the name suggests Stateful Widgets are made up of some ‘States’. The initState() is a method that is called when an object for your stateful widget is created and inserted inside the widget tree. It is basically the entry point for the Stateful Widgets. initState() method is called only and only once and is used generally for initializing the previously defined variables of the stateful widget. initState() method is overridden mostly because as mentioned earlier it is called only once in its lifetime. If you want to trigger it again you have to shift the control to an entirely new screen and a new state.