Dart: functions

I wanted to give you some short snippets about functions in dart. They can really help you. The first thing is how you can write a method in one line:

sayHello() => "Hello";

This is helpful for dummy stuff and so on. But now something more special. This parameters in square brackets is known as optional positional parameter. An example:

String saySomething(String thingToSay, [String name]){
 if(name != null){
 return "$thingToSay $name";
 } else {
 return thingToSay;
 }
 }

You then can call this method in 2 ways.

  1. print(saySomething(“I really like pasta”));
  2. print(saySomething(“I really like”, “Dart”));

But when you want to write more readable code, then try the optional named parameter.  For this you can use curly brackets. You can give a default value too. An example:

screamAndShout(String scream, {int times: 1}){
 for(int i = 0; i<times;i++){
 print(scream.toUpperCase());
 }
 }

The usage looks like this:

  1. screamAndShout(“i love dart”, times : 4);
  2. screamAndShout(“i love dart”);

I think all of this things can really help.

Yannick Signer