Hello Dart

For the examples in this section, we'll be using DartPad. It's an online tool that lets you play with Dart code from any browser, without having to install anything on your system. You can reach it at https://dartpad.dartlang.org/.

In this Hello Dart example, you'll see how to use DartPad, write the simplest Dart app, declare variables, and concatenate strings. Let's look at the steps for how we can go about it:

  1. When you open the tool for the first time, you should see something very close to the following image. On the left, you have your code, and when you click on the RUN button, you'll see the result of your code on the right:

  1. For our first example, let's delete the default code and write the following:
void main() {
String name = "Dart";
print ("Hello $name!");
}

If you run this code, you should see Hello Dart! on the right of your screen:

  1. The main() function is the starting point of every Dart application. This function is required, and you'll also find it in every Flutter app. Everything begins with the main() function.
  1. The String name = "Dart"; line is a variable declaration; with this instruction, you are declaring a variable called name, of type String, whose value is "Dart". You can use single (') or double (") quotation marks to contain strings, as follows:
String name = 'Dart';

The result would be identical:

  1. The print ("Hello $name!"); line calls the print method, passing a string. The interesting part here is that instead of doing a concatenation, by using the $ sign, you are inserting a variable into the string without closing it nor using the + concatenation operator. So, this is exactly like writing the following code:
print ("Hello " + name + "!");

There's also a generic variable declaration, in which you don't specify any type; you could write the same code like this:

void main() {
var name = "Dart";
print ("Hello $name!");
}
  1. In this case, you might think that name is a dynamic variable, but this is not the case. Let's try to change the variable type and see what happens:
void main() {
var name = "Dart";
name = 42;
print ("Hello $name!");
}

If you try running this code, you'll receive a compilation error as follows:

Error: A value of type 'int' can't be assigned to a variable of type 'String'. name = 42;  Error: Compilation failed.

Actually, you can declare a dynamic type as follows, although I believe you should avoid it in most cases:

void main() {
dynamic name = "Dart";
name = 42;
print ("Hello $name!");
}

If you try this code, you'll see Hello 42 in the console.

So the name variable, which was a string when we first declared it, has now become an integer. And as we are talking about numbers, let's delve into those next.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.12.50