Call for a definite value from an async method in flutter. waiting problem - flutter

How to write a function which fetches value from an async method ?
Future FetchValuefromService(String tk) async{ await .. //Fetch from api return value; }
void mainfunction(){ double newval =FetchValuefromService('hello'); //.... do something with newval. }
if i make mainfunction() async then the "do something" in mainfucntion will not get the double value. I need to get newval from service and then only i need to proceed.

Making a function async ables to use the await keyword in its body. Place it to the left of a Future<T> expression to pause the execution until the Future completes and the T value is obtained.
In your case, it would be double newval = await FetchValuefromService('hello');

Related

how do i force Flutter to run all the lines inside the function?

I have a this function that I need to run during initstate() in its entirety before building the widget. I have used this kind of code before in some parts of my app and it works there, but in this case, flutter jumps out before executing .then , goes to build the widget tree, and then returns back to the function but skips the remaining lines. I'm confused where I should properly put async-awaits to force it to finish the block. Also, can I ask where I can read an explanation of the proper flow of execution for flutter so that I can understand it more?
Future <bool> checkVendorStatus (buyerId) async {
var _result;
var vendorDocRef = await buyersInfoColl.doc(buyerId)
.collection("vendorsCalled")
.doc(auth.currentUser!.uid)
.get()
.then((value) async {
return await value.exists ? _result = true : _result = false;
}
);
return _result;
await is meant to interrupt the process flow until the async method has finished. then however does not interrupt the process flow (meaning the next instructions will be executed) but enables you to run code when the async method is finished.
you can write your code like this-
Future <bool> checkVendorStatus (buyerId) async {
var _result;
var vendorDocRef = await buyersInfoColl.doc(buyerId)
.collection("vendorsCalled")
.doc(auth.currentUser!.uid)
.get();
vendorDocRef.exists ? _result = true : _result = false;
return _result;
}

How can I read the string value from the _storageToken.read() call?

I have this construction in my homepage widget which is suppose to get the saved token. Now this returns a Future. So How can I read the token string? I tried storedToken.toString() but it returns Future<String?> not what I expected. I am expecting a String value like "fhsdjkfhs.djkfhsdjkfhsdjk"
void initState(){
const _storageToken = FlutterSecureStorage();
storedToken = _storageToken.read(key: 'jwt');
print(storedToken);
}
_storageToken.read() returns a Future, so you have to await it in order to get the value.
The problem is, you can't perform async/await action directly on the initState.
If you still want to call that _storageToken.read() on the initState, you can use this workaround.
void initState(){
/// Initialize Flutter Secure Storage
const _storageToken = FlutterSecureStorage();
/// Await your Future here (This function only called once after the layout is Complete)
WidgetsBinding.instance?.addPostFrameCallback((timeStamp) async {
final storedToken = await _storageToken.read(key: 'jwt');
print(storedToken);
});
}

In flutter, how to trigger something strictly after an async function is done executing?

Say I have a _mode property that I want to change in setState() when a button is pressed.
When the button is pressed (onPressed), I am calling this function,
Future <void> changeMode() async {
_result = await getResult(); // Returns a result. I want the mode to change AFTER the result is returned
setState((){
_mode = Modes.OFF;
});
}
What ends up happening is, the _mode is changed before the getResult() is done executing. How should I go fixing this?
When you use await inside a function, that function is in danger of blocking the main thread, so it must be marked as async.
Mark your function with async and it should work. Your state setting function also should be a parameter of setState().
Future<void> changeMode() async {
_result = await getResult(); // Returns a result. I want the mode to change AFTER the result is returned
setState(() {
_mode = Modes.OFF;
});
}

How to convert Future List instance to List String in flutter

I am saving strings list in shared procedure and fetching that like below
Future<List<String>> getList() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getStringList("key");
}
Issue is that I need to send that list to server but facing issue as I need to convert that future list to simple List
How can I do that? or is there any other way as I need to send list of ids save by user to server.
When you mark a function as async it will return a future.
If you dont wait for the future you will get 'Future instance' this means your future(data) is not available yet.
If you want to wait for the future(data) to be resolved you need to use the await keyword.
So in your case you can create a List<String> myList; then create a function to wait for the future and assign the data to the previous List.
List<String> myList;
void getStringList() async {
var tempList = await getList();
// Or use setState to assign the tempList to myList
myList = tempList;
}
Or use Then:
getList().then(List<String> myList {
// TODO: Send myList to server.
});
Hope this helpe!!
When you work with async data you should "wait" while data will not completely loaded. You can use await word in async methods like that:
foo() async {
final Future<List<dynamic>> futureList = fetchSomeFutureList();
final list = await futureList;
}
or use Future's then() method to delegate some work.
You also can wait for futures in widget tree using FutureBuilder.
Check Dart Docs page for see details.

Future<void> vs void

Say I want to create an asynchronous method. I can make its return type either Future void or simply "void" (as in examples below). Both ways seem to do the trick. So what's the difference between the two? When should I use Future void instead of void? Thanks!
Future<void> myMethod() async{
await myOtherMethod(); //myOtherMethod() has return type of Future<void>
print('something');
}
vs
void myMethod() async{
await myOtherMethod(); //myOtherMethod() has return type of Future<void>
print('something');
}
Use Future<void> where you want to
Call future functions:
myMethod().then((_) => ...).catchError((err) => ...);
Use await for more readable async code.
await myMethod();
await anotherMethod();
Use void where you want to fire and forget.
myMethod();
... do other stuff
The Future<void> is a lot more common. If you're not sure which one to use, use Future<void>.
Future<void> myMethod() async{ }
is a asynchronous function which means it let the app to work while waiting for some operation to finish(ex:Network Request).The Future fun(); is used while we need to perform operation that gives result in future such as network call.
void fun(){};
is function that doesnot return anything.