Let’s get ready to create our first app.
Flutter apps import
the Flutter framework at the top of the main.dart
file. This brings in the libraries necessary to display Flutter output:
import 'package:flutter/material.dart';
Every Dart app starts with the function void main()
. This is where our code starts running and is the entry point of the application.
void main() { }
The main
function invokes the runApp
function. runApp
takes in one Widget and displays it as a Flutter app. This widget is known as the root widget and is the starting point for our application. runApp()
on its own won’t compile though because it needs a widget:
runApp();
MaterialApp
is a widget designed to be the root widget of an app. MaterialApp provides vital services to widgets, such as telling them what colors to use and what direction to display text in. Dart prefers we use const
in front of the first widget for our app:
runApp( const MaterialApp() );
MaterialApp takes a home
parameter. In our examples, the home
element of our app will be the Scaffold widget:
const MaterialApp( home: Scaffold() )
While the MaterialApp provides core information, the Scaffold widget will provide a basic structure to our app. Later on, we will use some of its features to create menus and toolbars.
This leaves us with the final starting point for our application:
import 'package:flutter/material.dart'; void main() { runApp( const MaterialApp( home: Scaffold() ) ); }
In the next exercise, we will take a look at our first widget with content.
Instructions
Let’s recreate our application starting point.
import
the Flutter library at the top of the file.- Create a
main
. - Call
runApp
. - Place a
MaterialApp
widget inside ofrunApp
‘s parentheses. - Give the MaterialApp a
home
widget ofScaffold
. - Press the blue Run button. This should produce a blank application.
Seeing an empty screen with no error messages means you are successful.
Hint
These same steps are followed in the lesson text.
Solution
import 'package:flutter/material.dart'; void main() { runApp( const MaterialApp( home: Scaffold() ) ); }