Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading