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.
Related
I'm using a lambda expression in my C# script in my Unity project to call a function with a parameter when a DOTween callback is called.
It simply looks like this: animation.OnComplete(() => DestroyOnCompleted(children));
It works just fine, but I am note sure why a lambda expression is used in this case. I know it has something to do with delegates, but other than that, I'm not too sure; and I would like to explain it to my exam, if I get asked about it.
Could anyone enlighten me? :-)
Why not? ;)
I don't know that API too much but it seems like it is simply expecting something like
OnComplete(TweenCallback callback)
where TweenCallback from your usage basically seems to equal the c# built-in Action delegate and basically simply a parameter less void
public delegate void TweenCallback();
so whether you pass in this callback as a lambda like
animation.OnComplete(() => DestroyOnCompleted(children));
or anonymous method using the delegate operator like
animation.OnComplete(delegate { DestroyOnCompleted(children); });
or using a method
animation.OnComplete(OnCompletedAnimation);
...
private void OnCompletedAnimation()
{
DestroyOnCompleted(children);
}
is basically equivalent.
The main difference between the first two and the last one is: Where does children come from?
The lambda and delegate way allows you to pass in children from the current scope variables without having to store it in any field!
If you look at the documentation of DotTween, you see that row:
Now looking at the Source Code of DotTween, you can see the definition of TweenCallback:
public delegate void TweenCallback();
So the question now is, what is a delegate void in c#?
A delegate in c# is basically an object that "represent" a function.
But functions are not all the same, they can have parameters in input and return something (or return void).
To understand what kind of function does a delegate represent, try to just remove the keyword delegate.
For example, the TweenCallback without the keyboard delegate is:
public void TweenCaalback()
So the delegate represent a void function that has no parameters in input! (And it is Public).
What does it means represent a function?
It means that this is valid code:
void DoNothing()
{
}
TweenCallback x = DoNothing;
x();
So you can "assign functions" to a delegate that has the same function signature.
In this case, TweenCallback is a delegate void (), so you can assign to it a void() function.
What is a lambda?
A lambda is an expression of that style:
(string name, int age) => { return 3 };
you can read that as "string name and int age go in return 3"
That's a more concise way to describe that function:
int AnonymousFunction (string name, int age) {}
The main difference is that lambdas do not have any name. If you have not any parameter in input the lambda become like this:
() => {return 3;}
If you have only one statement inside the {} you are allowed to write it more shortly as
() => 3;
Final step
Is this valid code?
void DoNothing()
{
}
TweenCallback x = () => DoNothing();
Yes it is! Tween callback is expects a void () function.
() => DoNothing(); Is a lambda (un-named function) that takes nothing in input and calls some other function. It's the shorter version of () => {DoNothing();} that you have to think as void () {DoNothing();}
So when writing
animation.OnComplete(() => DestroyOnCompleted(children));
You are just passing a void () function to OnComplete Method, that makes sense because TweenCallback is a void () delegate.
Notes
As you can see, functions and lambdas expression can be converted implicitly to delegates. But you have to understand that they are all different things, and in more advanced coding scenarios that distinction is not just pure theory.
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.
Happened to me many times that forgettin to add ()=> ruined my code and contributed to weird bugs.
I mean this:
funtion(){
...
}
ElevatedButton(
onPressed: ()=> function()
Sometimes I am still not sure when I should use:
function or function() or ()=> function()
Can someone explain how to choose so code works properly? Thank you in advance
Given:
R f() {
...
}
f is a reference to a Function object that, when invoked, returns an object of type R.
f() actually invokes the function f. The result of the function call is an object of type R.
() => f() is equivalent to () { return f(); }. It creates a new Function object that, when invoked, then invokes f and returns its return value. It's the same thing as #1 (a Function object that returns an R when invoked) but in a more convoluted form. That is, your code:
onPressed: () => function()
essentially is:
onPressed: function
Happened to me many times that [forgetting] to add ()=> ruined my code and contributed to weird bugs.
That should be rare. If that's happening, you probably aren't using strong typing and are using dynamic types throughout your code. If you specify return types, argument types, variable types, etc. and use Dart analyzer, you usually should be able to catch misuses early without needing to run your code.
If your function and callback have the same parameter types you can simply call the function name alone. Like,
function() {
...
}
ElevatedButton(
onPressed: function,
);
If your function and the callback have the different paremter and you have to call a function alone. You can call the method by using lambda expression like below,
function() {
...
}
GestureDetector(
onTap:(details) => function(),
);
It's like
function() {
...
}
GestureDetector(
onTap:(details) {
function();
},
);
how can you use String theFlag anywhere else outside of this anonymous function
I had to make it an anonymous function as I failed to point a separate asynchronous function into onPressed in a RaisedButton as it only worked with onChanged now i just need to pass String theFlag to another widget in another screen
please help and mind the beginner question
onPressed:() async {
Locale _temp = await setLocale(LanguageClass.languageList()[index].langCode);
BldrsApp.setLocale(context, _temp);
String theFlag = LanguageClass.languageList()[index].langFlag ; //I need to use this elsewhere
print(theFlag);
},
You can do it like this,
String iCanBeAcessed; //make this variable somewhere else, so that you can use it anywhere.
//Inside your anonymous function
iCanBeAcessed=theFlag;
How can i use that?
You can declare it outside a class, and can use it anywhere in your project.
Example,
//imports
String iCanBeAcessed;
class yourClassName{
//All your other functions and build method
Now, import the dart file( where you have declared the iCanBeAcessed ) in the following manner.
import dartFile.dart as flagString;
//Now, you can use this variable anywhere!
Text(flagString.iCanBeAcessed),
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()