Hello Flutter
Learning objectives
- You know what Flutter is and how a simple Hello world! application is built with Flutter.
Flutter basics
Flutter is a framework for building applications for a wide variety of devices using a single codebase. It uses the Dart programming language and relies on a large collection of components from the framework.
Flutter applications consist of components (called widgets). The widgets form a hierarchy, which is similar e.g. to the Document Object Model used in building web applications.
Let's look into building a basic Flutter application used for displaying the text "Hello world!".
Hello world application
MaterialApp
Basic Flutter applications consists of a MaterialApp object, which provides convenience settings for the application. A basic Flutter application (with no content) is implemented as follows. The function runApp
that is called from main
starts the application that is given to it.
const?
Some classes in Flutter (and Dart) such as MaterialApp have constant (const
) constructors. Constant constructors are an optimization that allows creating immutable objects and reusing them over and over again.
The MaterialApp
class has a constructor with a named argument home
that is used to set contents of the application. Using the Text class, we can create an application that shows the text Hello world!
.
Scaffold
The above application looks, however, relatively ugly as no styles have been defined. The class MaterialApp is commonly used with the class Scaffold, which defines basic Material Design layout structure and settings to the application.
Scaffold has a constructor with a named argument body
which is used to set the body of the application (there are also other properties that we'll look into later). A Hello world!
-application with the Scaffold (and MaterialApp) in place looks as follows.
AppBar
The Scaffold has also a named argument called appBar
that is used to set an application bar commonly seen in applications. Application bars are implemented using the AppBar class, which allows -- among other things -- setting a title for the application.
When considering the above application, it could be represented as the following widget structure.
Center
When we consider the application, it still seems visually a bit off. This could, in part, be due to the body text not being aligned. To center the text, we use a class called Center, which is used to center its contents. The Center class has a constructor with a named argument child
, through which the centered contents are passed to it.
With the Center widget in place, the application would look as follows.