Flutter Dart Function as a Parameter to Another Function - flutter

I was looking into the documentation and failed to find an answer to my question:
Suppose I have a function the returns a Future<String> that I want to imbed in a second function which could take any other function that is of type Future<String>, the syntax -if I am not wrong- would be:
String functionTwo(Future<User> Function() putFunctionHere) async {
await code
return 'some string';
}
If I had to guess with regards to Dart syntax, I would say that it would be:
String functionTwo(Function putFunctionHere){...}
Which leads me to my question, why do we have to specify Future<User> Function() is it the only way?
And why do we have to put the parentheses next to Function

The syntax are as follow:
OutputType Function(ParameterType1 paramater1, ParameterType2 parameter2...) nameOfFunctionForUsageInsideTheMethod
So the following can be read we take a function as argument which must return Future<User> and takes no arguments.
Future<User> Function() putFunctionHere
This function can then be referred to as putFunctionHere like:
final value = await putFunctionHere()

Related

Difference between Function and Function() in flutter [duplicate]

This question already has an answer here:
Function and Function()
(1 answer)
Closed 5 months ago.
I have a doubt where I'm passing a function as a parameter, for onPressed, like event, I would declare a field like final void Function() onPressed, There are some code where I have seen declarring fields like Function someFunction, I would like to know what is the differnce between using Function and Function(). Thanks,
The main() function came from Java-like languages so it's where all programs started, without it, you can't write any program on Flutter even without UI.
The runApp() function should return a widget that would be attached to the screen as a root of the widget Tree that will be rendered
As we can see in doc, Function is:
part of dart.core;
/// The base class for all function types.
///
/// The run-time type of a function object is subtype of a function type,
/// and as such, a subtype of [Function].
Now, Function(), is literally a function, see the example:
Here you can use this:
final Function() func = () {};
ElevatedButton(
onPressed: func;
)
But you can not:
final Function func = () {};
ElevatedButton(
onPressed: func;
)
Here you get the following error:
The argument type 'Function' can't be assigned to the parameter type 'void Function()?'.dartargument_type_not_assignable
Otherwise, you can use:
Function func() {
return () {};
}
ElevatedButton(
onPressed: func;
)
Use Function somename when you need to return a function from a method.
Use Function() somename when you need to use this, literally, as a function.
As per Flutter docs:
Function is the base class of all the function types. It means it represents all the functions.
Adding parenthesis like: Function() makes it one without any parameter.
To sum up: Function is general and Function() is more specific.
Yep, lets take a look whats is braces actualy means.
The main difference between Method(); and Method, is that in first case, you call a method instant and its all. If you'l try to do var someStuff = Method(), someStuff will get a returning value of Method();
In second case, when you use Method, you actually do not call it, because its a link to a method. Because of it is a link, you cant pass an arguments (which places in braces), and if you try to make set variable like this: var someStuff = Method;, variable someStuff will contains a link to a original Method(), and you can call it in code, and it'l work same.
That means, when you pass a link to a onPressed:, and if link has right signature (in and out param), you haven't write whats goes in method and out, all what you should to do will looks like: onPressed: Method. Dart automatically understand, what params in and out, by comparing theirs signature.

Flutter source - Future<String?>? Function(String)

I'm new to flutter?
Can someone explain to me what the following line of code means?
typedef RecoverCallback = Future<String?>? Function(String);
This line is contained in the auth.dart file of the flutter_login plugin
https://github.com/NearHuscarl/flutter_login/blob/master/lib/src/providers/auth.dart
So Function(String) Where is it implemented?
typedef RecoverCallback = Future<String?>? Function(String);
It's function-type alias, gives a function type a name that you can use when declaring fields and return types.
As you can see in 45 line of class Auth implementation, that function you need to pass to the constructor of
new Auth(onRecoverPassword: yourFunction);
yourFunction must be a Function that take some String parameter and return Future<String?> or null;
The reason I want to understand the above line of code is because
final error = await auth.onRecoverPassword!(auth.email);
error = null;
but no mail is sent to auth.email.

GetX doesn't accept method parameters either

I cannot use the ".obs" property variables that I have created as parameters in my api service methods. and it gives the error The prefix 'coinTwo' can't be used here because it is shadowed by a local declaration.
Try renaming either the prefix or the local declaration.
I wrote the problem in getx, but they did not understand the problem.
I would appreciate it if you could take a look at my issue on github.
İssue link: text
I would appreciate it if you could take a look at my issue on github.
İssue link: text
Your problem is in the declaration of getOrderBookData
Instead of
getOrderBookData(coinOne.value, coinTwo.value) async {
...
you should either have
getOrderBookData() async {
...
//Do stuff with coinOne.value, coinTwo.value
...
OR
getOrderBookData(String firstCoin, String secondCoin) async {
coinOne.value = firstCoin;
coinTwo.value = secondCoin;
...
Edit
Seeing your post on GetX's Github, it looks like you're missing some basic understanding on how functions and methods work.
The code you wrote is the equivalent of the following method signature :
getOrderBookData("aValue", "anotherValue") async {
and it doesn't makes any sense.
Your method's signature should only declare the parameters it's expecting and their type.
You can also define a default value for those parameters if needed.
getOrderBookData({String firstCoin = coinOne.value, String secondCoin = coinTwo.value}) async {
in function declarations you just tell what type it is, and not actual values
So either do
getOrderbookData(String one, String two) async {
var res = await api.fetchOrderBookData(one, two);
purchase.value = res.result!.buy!;
sales.value = res.result!.sell!;
}
or hardcode it to always use coinOne and coinTwo and give no parameters
getOrderbookData() async {
var res = await api.fetchOrderBookData(coinOne.value, coinTwo.value);
purchase.value = res.result!.buy!;
sales.value = res.result!.sell!;
}
Make these changes and the error will be gone.
First, make a minor change to your getOrderBookData method:
void getOrderBookData() async {...} // Don't pass any parameter here.
And then make a change to your onInit method too.
#override
void onInit() {
getOrderBookData();
super.onInit();
}

How to test a void function in Dart?

I am new to unit tests in Dart/Flutter and I would like to write a test for a void function. When functions return something I am writing a test like this:
test('Gets user save', () async {
final userSave = await mockSource!.getUserSave();
expect(userSave!.age, equals(20));
});
In such a scenario like above expect can be used since getUserSave function returns a user model.
How about checking if test passes of fails for a void/Future function like below? I can not use expect because it does not return a value.
Future<void> clearUserSave() async {
DatabaseClient mockDBClient = MockDatabaseClientImpl();
mockDBClient.clear();
}
I use flutter_test and mockito for testing.
Typically a void function will produce a side effect of some sort. When writing a test for a void function, I would check whatever state is effected by the void function before and after calling the function to be sure that the desired side effect has occurred.
In this specific case, you are calling clear on a DatabaseClient. I don't know the specifics of the DatabaseClient api, but I would construct a test where the client contains some data before calling clear, and then check that the data is no longer there after calling clear.
Something along the lines of this:
Future<void> clearUserSave() async {
DatabaseClient mockDBClient = MockDatabaseClientImpl();
mockDBClient.add(SOMEDATA);
expect(mockDBClient.hasData, true);
mockDBClient.clear();
expect(mockDBClient.hasData, false);
}
you can add nullable variable and assign variable value in method, after call method check if this varaible isNotNull
like this:
test('Gets user save', () async {
await mockSource?.getUserSave();
final userSave=mockSource.user;
expect(userSave,isNotNull );
});
testing a function that return void :
expect(
() async => await functionThatReturnsVoid(),
isA<void>(),
);

Function and Function()

What is difference between Function and Function() in Dart/Flutter?
for example in such a code
final Function x;
final Function() x;
As stated in the Function documentation, it is:
The base class for all function types.
A variable declared with type Function therefore can be assigned any function. However, you won't get any type-safety when invoking it.
Meanwhile a Function() type is a function with an unspecified (i.e., dynamic) return type and that takes zero arguments.