Nur Rony
Polyglot Programmer, DevOps and Forever Learner

Dart: Function Definitions

Dart: Function Definitions

I am quite familiar with Javascript and Functions in Dart share a lot of characteristics with functions in JavaScript, but they aren't exactly the same.

A generic function definition in Dart looks like this

returnType functionName([[dataType param1],... dataType paramN]) {
  // function body

for example

void hello(String name) {
  print("hello $name!!!");

All Dart functions return something. If you don't return anything, return null is implicitly added to the end of your function.

In Dart 1.x types were optional but Dart 2.x throws error if you ommit types

Dart also has fat-arrow functions (like ES6), but they don't work exactly the same way. You only use these in Dart if the function can be condensed to one line:

void hello(String name) => print("hello $name!!!");

Another thing that you must remember about fat-arrow functions is only an expression—not a statement—can appear between the arrow (=>) and the semicolon (;). For example, you can’t put an if statement there, but you can use a conditional expression.