How can i return a string from a future function?
Future<String> functionA() async {
var x = await fetchX();
return x;
}
Future<String> fetchX() {
return Future.delayed(Duration(seconds: 4), () => 'example');
}
Future<String> la() async {
print(await functionA()); //this works correctly
return await functionA(); //this return always an instance of Future
}
How can i return "example" from the future function, there is a method to do it, and where is my error?
Future<String> fetch() async {
return
http.get('url')
.then((response) => response.body);
}
That way you can sneak a .catchError into there. :)
You need to specify what your function will return. All you have to do is add Future to the beginning of the method.
Future<String> fetch() async {
final response = await http.get('url');
String conteggio = response.body;
return conteggio;
}
And you have to do this in a method. You can only assign constant values in fields other than methods.
Related
Can some one help me to identify the issue in below piece of code
void main() async {
bool c =getstatus();
print(c);
}
Future<bool> getMockData() {
return Future.value(false);
}
bool getstatus() async
{
Future<bool> stringFuture = getMockData();
bool message = stringFuture;
return(message); // will print one on console.
}
To get values from a Future(async) method, you have to await them. And after await the variable you get is not a Future anymore. So basically your code should look like this:
void main() async {
bool c = await getstatus();
print(c);
}
Future<bool> getMockData() {
return Future.value(false);
}
Future<bool> getstatus() async {
bool message = await getMockData();
return message;
}
Future<bool> stringFuture = await getMockData();
an async method must return Future of something then in the main you have to get the bool value by writing await
void main() async {
bool c = await getstatus();
print(c); // will print false on the console.
}
Future<bool> getMockData() {
return Future.value(false);
}
Future<bool> getstatus() async {
Future<bool> stringFuture = await getMockData();
return stringFuture; // will return false.
}
I have a method createClient which return Future value and this method call another _getConfig method which returns a response as a Function callback, is there any way that in createClient method I can return Future from response of _getConfig method.
Future<String> createClient() async {
_getSocketConfig((socketConfig) => Future.value(
socketConfig,
));
}
void _getConfig(Function(String) onConfigFetch) async {
onConfigFetch("profileId");
}
I'm not sure if I understand, but is it this what you want?
Future<String> createClient() async {
return _getSocketConfig((socketConfig) => Future.value(
socketConfig,
));
}
Future<String> _getSocketConfig(Function(String) onConfigFetch) async {
return onConfigFetch("profileId");
}
I have a function A() which return a string and I need to receive the string and print the string using then() method in dart
Future<String> A() async {
return "Hello";
}
await A().then((value) => print(value));
I want to get the "Hello" printed but it prints null. How to do this ?
await should be used in an async function. But you have used await outside of the async function.
Try removing await outside.
Future<String> A() async {
return "Hello";
}
A().then((value) => print(value));
I have a list List<Item> list and a function Future<bool> myFilter(Item).
Is there a way to filter my list using the Future returning function myFilter()?
The idea is to be able to do something like this:
final result = list.where((item) => myFilter(item)).toList();
But this is not possible since where expects bool and not Future<bool>
Since the iteration involves async operation, you need to use a Future to perform the iteration.
final result = <Item>[];
await Future.forEach(list, (Item item) async {
if (await myFilter(item)) {
result.add(item);
}
});
You can iterate over your collection and asynchronously map your value to the nullable version of itself. In asyncMap method of Stream class you can call async methods and get an unwrapped Future value downstream.
final filteredList = await Stream.fromIterable(list).asyncMap((item) async {
if (await myFilter(item)) {
return item;
} else {
return null;
}
}).where((item) => item != null).toList()
You can try bellow:
1, Convert List => Stream:
example:
Stream.fromIterable([12, 23, 45, 40])
2, Create Future List with this function
Future<List<int>> whereAsync(Stream<int> stream) async {
List<int> results = [];
await for (var data in stream) {
bool valid = await myFilter(data);
if (valid) {
results.add(data);
}
}
return results;
}
Here's a complete solution to create a whereAsync() extension function using ideas from the accepted answer above. No need to convert to streams.
extension IterableExtension<E> on Iterable<E> {
Future<Iterable<E>> whereAsync(Future<bool> Function(E element) test) async {
final result = <E>[];
await Future.forEach(this, (E item) async {
if (await test(item)) {
result.add(item);
}
});
return result;
}
}
You can now use it in fluent-style on any iterable type. (Assume the function validate() is an async function defined elsewhere):
final validItems = await [1, 2, 3]
.map((i) => 'Test $i')
.whereAsync((s) async => await validate(s));
Try this:
final result = turnOffTime.map((item) {
if(myFilter(item)) {
return item;
}
}).toList();
I'm trying to pass as parameter of a method, a function that returns Future<Response>.
I tried to do
Future<String> _execute(Function<Future<Response>>() function) async { }
but it does not even compile.
What's the correct syntax?
You can do it like this,
Future<String> _myFunction(Future<Response> Function() function) {
...
}
You just need to specify that your parameter is a Function:
Future<bool> kappa() async{
await Future.delayed(Duration(seconds: 1));
return true;
}
Future<bool> foo(Function f) async{
var k = await f();
return k;
}
void main() async{
print(await foo(kappa));
}
This will print true. In your case, your function parameter can be:
Future<String> _execute(Function function) async { }