Chapters

Hide chapters

Dart Apprentice: Fundamentals

First Edition · Flutter · Dart 2.18 · VS Code 1.71

Dart Apprentice: Fundamentals

Section 1: 16 chapters
Show chapters Hide chapters

1. Hello, Dart!
Written by Jonathan Sande

This first chapter is designed to help you set up your development environment so that you can get the most out of the following chapters.

There are several different tools that Dart developers use when building apps:

  • DartPad: This is a simple browser-based tool for writing and executing Dart code. It’s available at dartpad.dev.

DartPad
DartPad

  • IntelliJ IDEA: IntelliJ is a powerful Integrated Development Environment, or IDE, that supports Dart development through a Dart plugin. Although Android Studio, a popular IDE for Flutter development, is built on IntelliJ, this book recommends that you use plain IntelliJ for pure Dart projects. The IntelliJ Dart plugin makes this an easier task than writing Dart code in Android Studio.

IntelliJ IDEA
IntelliJ IDEA

  • Visual Studio Code: Also known as VS Code, this is a lightweight IDE with a clean and simple interface. It fully supports Dart development with its Dart extension.

Visual Studio Code
Visual Studio Code

  • Other editors: There are also Dart plugins from the community for Eclipse, Emacs and Vim. You can even create your own Dart plugin for other editors and IDEs that support the Language Server Protocol (LSP). If you know how to do that, though, you can skip this chapter. Actually, you can probably skip the whole book.

This book uses Visual Studio Code for all of the examples contained within, but if you have another IDE you prefer, then by all means, continue using that one for your Dart development. If you don’t have a preference, though, you’ll find using VS Code an enjoyable experience. VS Code also supports Flutter development through an extension, so you won’t be limiting yourself for future Flutter development if you choose to go the VS Code route now.

Installing Visual Studio Code

Visual Studio Code is a cross-platform, open-source IDE from Microsoft. It runs on Windows, MacOS and Linux, so unless the only device you’ve got at your disposal is a mobile phone, then you’re covered!

Note: If you do only have a mobile phone, don’t despair! You can run the majority of the code examples in this book on dartpad.dev, which should work fine in any modern mobile browser.

Download Visual Studio Code at code.visualstudio.com, and follow the directions provided on the site to install it.

You’ll also need the Dart SDK, which you’ll install in the next section.

Installing the Dart SDK

The Dart Software Development Kit, or SDK, is a collection of command-line tools that make it possible to develop Dart applications.

Go to dart.dev/get-dart and follow the directions on that site to download and install the Dart SDK on your platform. If you get an error, try copying the error message and searching for it in Google. Chances are you’re not the first person have that problem!

Note: Flutter comes with a copy of the Dart SDK, so if you’ve already installed a recent version of Flutter, then you’re good to go. At the time of this writing, the current stable release of Flutter was 3.3, which includes Dart 2.18.

Verifying the Dart SDK Installation

After you’ve installed Dart, run the following command in a terminal to ensure that it’s working:

dart --version

You should see the current Dart version displayed.

Dart SDK version: 2.18.2 (stable)

If yours is less than 2.18, you should upgrade to the latest version. Some examples in this book won’t work with older versions of Dart.

For those using the Dart SDK packaged with Flutter, you can upgrade like so:

flutter upgrade

Contents of the SDK

Now check out what the Dart SDK offers you by entering the following command in the terminal:

dart help

You’ll see a list of tools that make up the SDK. Although you won’t directly interact with most of them in this book, it’s helpful to know what they do:

  • analyze: Your IDE uses this tool to tell you when you’ve made a mistake in your code. The sooner you know, the sooner you can fix it!

  • compile: This tool compiles Dart code into an optimized native executable program for Windows, Linux or macOS. This is known as ahead-of-time, or AOT, compilation. Alongside native executables, web technologies are another major focus for Dart, so you can also use the compile tool to convert Dart code to JavaScript.

  • create: This is for creating new Dart projects, which you’ll do yourself in just a minute.

  • devtools: These are a set of tools to help you with tasks like debugging or profiling the CPU and memory usage of a running app.

  • doc: If your code has documentation comments, which you’ll learn about in the next chapter, this tool will generate the HTML needed to display the comments as a web page.

  • fix: One of Dart’s goals is to continue evolving as a language without becoming bloated by obsolete, or deprecated, code. The fix tool is there to help developers update their old projects to use the shiniest new Dart syntax.

  • format: It’s easy for the indentation in your code to get messed up. This nice little tool will automatically fix it for you.

  • migrate: Version 2.12 was a major update to the Dart language with the addition of sound null safety, which you’ll learn about in Chapter 11, “Nullability”. This tool helps migrate old projects to use null safety. Since you’re starting fresh, though, you won’t need to migrate anything. Lucky you!

  • pub: Pub is the name of the package manager for Dart, and pub is the tool that handles the job. A package is a collection of third-party code that you can use in your Dart project. This can save you an incredible amount of time since you don’t have to write that code yourself. You can browse the packages available to you on Pub by visiting pub.dev.

  • run: This runs your Dart program in the Dart Virtual Machine, or VM. You’ll use the Dart VM to compile your code right before it’s needed. In contrast to AOT, this is known as just-in-time, or JIT, compilation, which will let you make small changes to your code and rerun it almost instantly. This is especially useful for applications like Flutter where you need to make lots of little changes as you refine the UI.

  • test: Dart fully supports unit testing, and this tool will help you get that done.

Dart on the Command Line

Now that you have the Dart SDK installed, you’re going to use the Dart VM to run a few lines of code, first in a single file and then as a full project.

Running a Single Dart File

Find or create a convenient folder on your computer where you can save the Dart projects you create in this book. Create a new text file in that folder and name it hello.dart.

Writing the Code

Next, add the following Dart code to that empty file:

void main() {
  print('Hello, Dart!');
}

main is the name of the function where all Dart programs start. Inside that function, you call another function, print, which displays the text Hello, Dart! on the screen.

Running the Code

Save the file, and then run the following terminal command in the same folder as hello.dart:

dart run hello.dart

The run keyword is the run tool from the Dart SDK that you learned about earlier. It runs the code in hello.dart in the Dart VM.

You should now see the following output in the console:

Hello, Dart!

Congratulations! You’ve written and run your first Dart program.

Setting Up a Full Dart Project

It’s nice to be able to run a single file, but as you build bigger projects, you’ll want to divide your code into manageable pieces and also include configuration and asset files. To do that, you need to create a full Dart project. Remember that create tool? The time has come.

Creating the Project

Go to the location where you want to create your project folder, and then run the following command in the terminal:

dart create hello_dart

This creates a simple Dart project with some default code.

Running the Project

Enter the new folder you just created like so:

cd hello_dart

Now run the project with the following command:

dart run bin/hello_dart.dart

You’ll see the text Hello world: 42!, which is the output of the code in the default project that the create tool generated.

The run keyword is optional. Run the project again without it:

dart bin/hello_dart.dart

Again, Hello world: 42! is the result.

The Structure of a Dart Project

Take a look at the structure and contents of the hello_dart folder:

The purposes of the most important items in that folder are as follows:

  • .gitignore: Tells Git which Dart-related files it doesn’t need to bother saving to GitHub. Or whatever other Git repository you’re using.
  • analysis_options.yaml: Holds special rules that will help you detect issues with your code, a process known as linting.
  • bin: Contains the executable Dart code.
  • hello_dart.dart: Named the same as the project folder, the create tool generated this file for you to put your Dart code in.
  • CHANGELOG.md: Holds a manually-curated, Markdown-formatted list of the latest updates to your project. Whenever you release a new version of a Dart project, you should let other developers know what you’ve changed.
  • lib: Stands for “library”. In larger projects, you’ll have many .dart files that you’ll organize under the lib folder. Similar to how a normal library holds a collection of books that you can borrow, a library in the Dart world holds a collection of code that you can use elsewhere.
  • pubspec.yaml: Contains a list of the third-party Pub dependencies you want to use in your project. The name “pubspec” stands for “Pub specifications”. You also set the version number of your project in this file.
  • pubspec.lock: Specifies the precise version of each dependency that the project is using. This is helpful for teams to ensure that everyone is using the same dependencies.
  • README.md: Describes what your project does and how to use it. Other developers will appreciate this greatly.
  • test: Stores your test files. Good developers write code to verify that their programs behave as expected.

Note: YAML stands for “YAML Ain’t Markup Language”, one of those recursive acronyms that computer programmers like to amuse themselves with. YAML is a clean and readable way to format configuration files, and you’ll come across this file type often in your Dart career.

Using VS Code for Dart Development

You’ve created and run a project from the command line, but it’s also possible to do the same thing from within VS Code. This section will walk you through that process.

Installing the Dart Extension

Open Visual Studio Code, and on the left-hand side you’ll see a vertical toolbar called the Activity Bar. Click the Extensions icon, which looks like four boxes. Then type dart in the search area. When the Dart extension appears, click the Install button to install it.

Now your VS Code installation supports Dart. Next, you’ll learn how to create a Dart project in VS Code.

Creating a New Dart Project

The Dart extension in VS Code makes it easy to create a new Dart project. To see how this works, you’ll recreate the same project that you previously created from the command line.

To start, delete your old hello_dart folder and its contents.

You can create a new project from the Command Palette. To access the Command Palette, either go to View ▸ Command Palette… in the menu, or press the shortcut Command+Shift+P on a Mac or Control+Shift+P on a PC.

Start typing dart to filter the list of commands. Then choose Dart: New Project.

Next, choose Console Application from the list.

Choose a location to save the project folder that VS Code will create, and name the project hello_dart.

If you see a dialog asking whether to use the recommended VS Code settings for Dart and Flutter, choose Yes.

Browsing the Generated Code

Open the file hello_dart.dart in the bin directory, and you’ll see it contains the following code:

import 'package:hello_dart/hello_dart.dart' as hello_dart;

void main(List<String> arguments) {
  print('Hello world: ${hello_dart.calculate()}!');
}

You don’t need to know how all of that works yet, but here are a few notes:

  • The line beginning with import is grabbing the calculate function from the hello_dart.dart file in the lib folder. You’ll learn about importing and functions later in the book.
  • The List<String> arguments portion is only necessary when creating command-line apps that take arguments. You won’t be creating command line apps in this book.

Simplifying the Project

The generated code is great for showing how Dart works, but this book is going to start even simpler. That means you can cut some things out.

Replace the code in bin/hello_dart.dart with the following three lines:

void main() {
  print('Hello, Dart!');
}

Then delete the lib and test folders. You’ll find an option to delete if you right-click the folder names.

These folders serve important functions, but they aren’t necessary when you’re just getting started.

Running Dart in VS Code

To run your code, make sure you have the bin/hello_dart.dart file open. Then click the word Run that appears directly over the main function.

You’ll see Hello, Dart! appear in the debug console.

Exploring the VS Code UI

This is a good opportunity to explore the various parts of the Visual Studio Code user interface.

The numbers below correspond to the various parts of the IDE:

  1. Activity Bar: Choose which content to show in the side bar.
  2. Side Bar: The Explorer is displaying the current project and file.
  3. Editor: Write your Dart code here.
  4. Panels: Show program output, run terminal commands and more.
  5. Status Bar: Display information about the current project.

More Ways to Run Your Project

You ran your project earlier by pressing the Run label over the main function. Here are three more ways that you can run your project:

  1. Choose Run ▸ Start Debugging from the menu.
  2. Press F5.
  3. Click the Start Debugging button in the top right corner.

All of these do the same thing. This time use F5 to run the program, and you’ll see Hello, Dart! appear in the debug console again.

Excellent! You’re all set to explore Dart further in the rest of this book.

Key Points

  • Visual Studio Code is an Integrated Development Environment (IDE) that you can use to write Dart code when you have the Dart extension installed.
  • The Dart SDK provides the underlying tools needed to compile and run Dart apps.
  • Dart code run from the command line or in VS Code uses the Dart Virtual Machine.
  • The VS Code window is divided into the Activity Bar, Side Bar, Editor, Panel, and Status Bar.
  • Pub is the package manager that Dart uses to add third-party source code to your projects.

Where to Go From Here?

If you’re new to Visual Studio Code, there’s a lot more to learn about it. You can find many instructional resources by going to the Help menu.

Most of the time, you’ll write Dart code using VS Code on a computer, but if you find yourself waiting in a long line at the supermarket, you can pass the time by writing Dart code at dartpad.dev, which will run on your mobile browser. Try out the sample Dart and Flutter projects there. If your device screen is too small to edit the code easily, go to your browser settings and view the page as a desktop site.

Now that you have your programming environment all set up, you’ll go on to start writing real Dart code in the next chapter. See you there!

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.