Understanding Functions in Dart with Example

funtions in dart

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.

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

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

Leave a Reply

Your email address will not be published. Required fields are marked *