Functions and methods
As we discussed previously, functions and methods are self-contained chunks of code that work on a specific task. Note that the syntax of methods and functions is identical, so where I refer to functions in this section, I am also referring to methods. Let's look at another example of a function, as follows:
String sayHello() { return "Hello world!"; }
This sayHello
function structure is very similar to the main
function we explored previously but also includes a return type of String
, so the function must have a return
statement at the end that returns a value of the expected type. In this example, the function returns a String
literal of "Hello world!"
. If the function could return a String
literal or null
then, as we saw in the Null safety section, we would mark the function's return type as String?
.
Note that the function return type can be omitted because the Dart analyzer can infer the return type from...