Search code examples
dartinline-functions

flutter anonymous / inline functions for widget properties


I am new to dart and flutter, I am trying to use an inline function to return a value.

SizedBox(
  height: _getheight()
),

double _getheight(){
//do some stuff
return 20.0;
}
//WORKS
SizedBox(
height: (){return 20.0;}
),
//(Won't build)

error: The argument type 'double Function()' can't be assigned to the parameter type 'double'.

SizedBox(
 height: (){return 20.0;} as double
),

--builds but fails during runtime error: type '() => double' is not a subtype of type 'double' in type cast


Solution

  • height are taking a value of the type double. In you first example, you are executing _getheight() and then gives the result of this execution as the parameter named height.

    In you second example you are trying to give height an function as argument (typed as double Function()) which are not allowed since height is defined to take a double.

    You could then do:

    SizedBox(
    height: (){return 20.0;}()
    ),
    

    Which will execute the method (see the last ()) and use the returned value as argument to height.