In Dart, how to pass a function as parameter that returns a Future - flutter

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 { }

Related

Flutter ensure I have a value in Async/Await and init functions [duplicate]

This question already has answers here:
What is a Future and how do I use it?
(6 answers)
Closed 20 days ago.
How can I make sure I have a state variable available after an async function call? My belief is because getValues() is async, it should "wait" until moving on to the next line. Thus, getValues() shouldn't exit and configValue() shouldn't be invoked until after my call to setState has finished. However the behavior I'm seeing it that values is an empty array in my Widget.
late List values = [];
#override
void initState() {
super.initState();
getValues();
configValue();
}
getValues() async {
final String response = await rootBundle.loadString('assets/values.json');
final vals = await json.decode(response)['values'];
setState(() {
values = vals;
});
}
void configValue() {
// How to make sure I have values[0] here?
}
Thanks in advance!
You can change your getValues to this:
Future<List> getValues() async {
final String response = await rootBundle.loadString('assets/values.json');
final vals = await json.decode(response)['values'];
return vals;
}
then create another middle function like this:
callasyncs() async {
var result = await getValues();
configValue(result);
}
and call it inside initState like this:
#override
void initState() {
super.initState();
callasyncs();
}
also change your configValue to this:
void configValue(List values) {
// now you have updated values here.
}
here your both configValue and getValues are separated from each other and also your configValue will wait for the getValues result.
you need to use await before the method to complete the future. also can be use .then.
Future<void> getVids() async { //I prefer retuning value
final String response = await rootBundle.loadString('assets/values.json');
final vals = await json.decode(response)['values'];
setState(() {
values = vals;
});
}
void configValue() async {
await getVids();
}
Try the following code:
List? values;
#override
void initState() {
super.initState();
getValues();
configValue();
}
Future<void> getVids() async {
final String response = await rootBundle.loadString('assets/values.json');
final vals = await json.decode(response)['values'];
setState(() {
values = vals;
});
}
void configValue() {
if (values != null) {
if (values!.isNotEmpty) {
…
}
}
}

Instance of _Future<int> is all I get when I try to get the total 'document' of my 'collection' in Firestore

Following is my code. I'm trying to get all the 'Babies' which are in documents:
class _HomePageeState extends State<HomePagee> {
String t_babies = getCount().toString();
}
Future getCount() async {
return FirebaseFirestore.instance.collection('Babies').snapshots().length;
}
Instead I get this error: instance of \_future\<int\>
Here is my Database. I expect to get 2 counts:
You need to use await when getting Future values and also you should pass Future and the type Future<int>:
Future<int> getCount() async {
return await FirebaseFirestore.instance.collection('Babies').snapshots().length;
}
and also get the method using await but inside and async function:
void example() async { // <---- here the async you need to add to use await
int babiesLength = await getCount(); // here use await
}
You should use setState to update the string , because the fetch takes time as it involves network.
String t_babies = '';
Future<void> _getCount() async {
setState((){
t_babies = FirebaseFirestore.instance.collection('Babies').snapshots().length.toString();
});
}
#override
void initState() {
super.initState();
_getCount();
}

How to receive the callaback value from a function in dart?

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));

Return String from a Future function

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.

Is there any difference between just returning a value and by using Future.value(); in Dart?

For example, is there any difference between those two code snippets? In dartpad, they return the same thing at the same time.
Does the function itself infer the returning value as bool from the function declaration (Future<bool>) so that using just 'return' is okay or is there any specific situation that make difference?
A:
Future<bool> anyFunction() async {
print('start');
var temp = Future.delayed(Duration(seconds: 5));
bool result = await getSomeResult();
print('end');
return result;
}
B:
Future<bool> anyFunction() async {
print('start');
var temp = Future.delayed(Duration(seconds: 5));
bool result = await getSomeResult();
print('end');
return Future<bool>.value(result);
}