Dart is a strictly typed programming language that is used in the Flutter framework to develop cross platform mobile apps maintain by Google.
Functions in Dart are very powerful and flexible. Dart Functions works much like function in JavaScript.
Understanding Functions in Dart
Functions in Dart are objects and have the type Function. Functions can be assigned to values, passed in function arguments, and used as function return values. It’s very easy to create high-order functions in Dart.
A function may have zero or many parameters. Some parameters are required, while some are optional. Required arguments come first in the parameters list, followed by optional parameters. Optional positional parameters are wrapped in [].
When a function has a long list of parameters, it’s hard to remember the position and meaning of these parameters. It’s better to use named parameters. Named parameters can be marked as required using the @required annotation.
Parameters can have default values specified using =. If no default value is provided, the default value is null.
import 'package:meta/meta.dart'; int sum(Listlist, [int initial = 0]) { var total = initial; list.forEach((v) => total += v); return total; } String joinToString(List list, {@required String separator, String prefix = ", String suffix = "}) => '$prefix${list.join(separator)}$suffix'; void main() { assert(sum([1, 2, 3]) == 6); assert(sum([1, 2, 3], 10) == 16); assert(joinToString(['a', 'b', 'c'], separator: ',') == 'a,b,c'); assert( joinToString(['a', 'b', 'c'], separator: '-', prefix: '*', suffix: '?') == '*a-b-c?'); }
In above example, the function sum() has an optional positional argument initial with the default value 0.
The function joinToString() has a required named argument separator and two optional named arguments prefix and suffix.
The arrow syntax used in joinToString() is a shorthand for function body with only one expression. The syntax => expr is the same as { return expr; }. Using arrow syntax makes code shorter and easier to read.
Sometimes you may not need a name for a function. These anonymous functions are useful when providing callbacks.
In bellows example, an anonymous function is passed to the method forEach().
var list = [1, 2, 3]; list.forEach((v) => print(v * 10));
Dart Function Footnotes
Dart is a class-based, object-oriented programming language that simplifies the development of structured modern apps, scales from small scripts to large applications, and can be compiled to JavaScript for use in any modern browser.
Read more and Some refarence about Dart Functions:
If you still find it a bit confusing about Fucntions in Dart, do reach out to me on Twitter or add your comment in the comment box below.
Happy coding. 😎😎