What does the paranthesis at the end of an anonymous function signify in Flutter?

Advertisements

The following code snippet showed me an error,which is:’The argument type ‘List Function()’ can’t be assigned to the parameter type ‘List’.’

home:Scaffold(
        body:Column(
          children: (){
            List <Widget> w=[];
            for(int i=0;i<str.length;i++){
              w.add(Text(str[i]));
            }
            return w;
          },

When I changed it like so:

home:Scaffold(
        body:Column(
          children: (){
            List <Widget> w=[];
            for(int i=0;i<str.length;i++){
              w.add(Text(str[i]));
            }
            return w;
          }(),// <- Notice the () at the end here

When I included the last two ‘()’ in the anonymous function, the compiler showed no error. What is even happening ? what does those two paranthesis at the end signify? Why was the error lifted, what is happening in the background?

>Solution :

In Dart, placing () after a function call invokes that function immediately. This is known as "calling" the function.

The children property of the Column widget expects a list of widgets (List). However, in the original code, you were passing a function () {} instead of the list. By adding () at the end of the function, you are invoking it immediately, which returns the list of widgets as expected by the children property.

So, essentially, by adding () at the end of the function, you are turning the function itself into a value (the result of the function call), which in this case is a List, as expected by the children property.

Therefore, the error is resolved because now you are passing a List to the children property, which matches the expected type.

Leave a ReplyCancel reply