Skip to main content

Creating your first app

About 6 min

Creating your first app

Create a new Flutter project

Folder name

  • Make sure that all the parent folders don't contain spaces or special characters as this might break the build!

There are two ways to create a new Flutter project:

  • Command line: flutter create hello_flutter
    • hello_flutter = application name
  • VS Code
    • View - Command Palette (or Ctrl+Shift+P)
      command palette
    • Flutter: New Project
      new project
    • Choose the Application template template
    • Choose the folder where you save all your Flutter projects (create one if needed)
    • Enter the project name hello_flutternew project name

REMARK

There are some conventions about the name of a Flutter application:

  • only lower case characters
  • separate words are combined with underscore(s)

Run the Flutter App

You can run your Flutter application in three different ways.

Chrome

  • The simplest method (and fastest) is to just use your browser.
  • Click in the status bar at the bottom right on Windows (windows-x64)
device
device

and choose Chrome as the device to use.

device
device
  • To run/debug your app you have to click on the triangle icon in the left bar
device
device
  • Click on the 'Run and Debug' button to run the app
device run
device run
  • After a while
device run
device run

Warning

Note, however, that your browser will not support all the features of a real smartphone. For example, you won't be able to test out the AR part via your browser. But the Flutter part of the course should work without any problems.

Your smartphone

  • If you set up developer options on your smartphone and give permission for USB debugging, you can run your App on your smartphone. Click in the status bar at the bottom right and choose your smartphone as the device to use.

  • Click on the 'Run and Debug' button to run the app

device run
device run

First run

  • The first run might take some time, as there are probably some more android specific installations needed
  • The result:
Hello Flutter

An Emulator

The last option is to use an emulator. This is the least convenient option. You must first create an emulator via Android Studio (see previous page).

Simplify

  • The default MyApp class is too complex to explain how Flutter works. Therefore we are going to simplify it.
  • Delete the file widget_test.dart in the test folder in the root of your project
  • Delete all the contents of the lib\main.dart file and add the following content:
import 'package:flutter/material.dart';

void main() {
  runApp(
    const Center(
      child: Text(
        "Hello Flutter!",
        textDirection: TextDirection.ltr,
      ),
    ),
  );
}
 
 
 
 
 
 
 
 
 
 
 
 
  • Re-run your app (in your web browser, the background may be grey.):
run

TIP

When you are programming in Flutter you will see a lot of rounded brackets. It is a good idea, when nesting those brackets, to put a comma behind these brackets and pressing alt-shift-f afterwards to format your code.

Widgets

In Flutter (almost) everything is a Widget! Let's have a look at our hello_flutter app:

import 'package:flutter/material.dart';

void main() {
  runApp(
    const Center(
      child: Text(
        "Hello Flutter!",
        textDirection: TextDirection.ltr,
      ),
    ),
  );
}
 

 
 
 
 

 




codedescription
import 'package:flutter/material.dart';this package contains all Flutter widgets implementing Material Design
mainentry point of a Flutter application
runAppshows a widget on the screen of your device
Centera widget that centers its child within itself (text is displayed in center of app)
Texta widget that displays a string of text with single style
textDirectionproperty of Text Widget

OFFICIAL DOCUMENTATION

All the widgets, classes, methods, properties, ... are described in detail in the Flutter - Dart API docsopen in new window

Material design

  • It's easy to prettify our user interface by using Material Design. There are a lot of widgets available in the material package that we imported before
  • Update the runApp method as shown below:
void main() {
  runApp(
    const MaterialApp(
      title: 'Hello Flutter App',
      home: Material(
        color: Colors.deepPurple,
        child: Center(
          child: Text(
            "Hello Flutter!",
            textDirection: TextDirection.ltr,
            style: TextStyle(color: Colors.white, fontSize: 36.0),
          ),
        ),
      ),
    ),
  );
}


 
 
 
 
 



 






codedescription
const MaterialApp()defines that the app will use Material Design
titletitle of the app used by the device to identify the app for the user
homeproperty to define the widget for the default route of the app
Material()material widget
colorbackground color of the material widget
childproperty to define the one and only possible child widget of the material widget
styleproperty to apply a TextStyle to the text

Scaffold class

  • Implements the basic material design visual layout structure
  • This class provides APIs for showing drawers, snack bars, and bottom sheets
  • Via the appBar property we can add an application bar to the app

void main() {
  runApp(
    MaterialApp(
      title: 'Hello Flutter App',
      home: Scaffold(
        appBar: AppBar(
          title: const Text("Title in App Bar"),
        ),
        body: const Material(
          color: Colors.deepPurple,
          child: Center(
            child: Text(
              "Hello Flutter!",
              textDirection: TextDirection.ltr,
              style: TextStyle(color: Colors.white, fontSize: 36.0),
            ),
          ),
        ),
      ),
    ),
  );
}





 
 
 

 













codedescription
Scaffold()class that implements the basic material design visual layout structure
appBarproperty from Scaffold class to define an application bar
AppBar()class to implement the application bar
titleproperty from AppBar class for the title of the application bar
bodyproperty from Scaffold class to define the primary content of this scaffold

Organizing your code

  • Flutter applications are written in Dart
    • Dart is an object oriented programming language, so we can make use of classes, objects, methods, ...
  • At this moment we have a very large main method
  • We can reorganize our code by using some object oriented programming techniques
void main() => runApp(const HelloFlutterApp());

class HelloFlutterApp extends StatelessWidget {
  const HelloFlutterApp({super.key});

  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Hello Flutter App',
      home: Scaffold(
        appBar: AppBar(
          title: const Text("Title in App Bar"),
        ),
        body: const Material(
          color: Colors.deepPurple,
          child: Center(
            child: Text(
              "Hello Flutter!",
              textDirection: TextDirection.ltr,
              style: TextStyle(color: Colors.white, fontSize: 36.0),
            ),
          ),
        ),
      ),
    );
  }
}
 

 
 


 




















codedescription
void main() => ...creates object (instance) from HelloFlutterApp class
class HelloFlutterApp extends StatelessWidgetHelloFlutterApp class extends the StatelessWidget class. The class will inherit from the StatelessWidget class, which is a generic widget that never needs to change. StatelessWidget is the super class, HelloFlutterApp the sub class. This is how you implement inheritance in Dart
const HelloFlutterApp({super.key});All widgets should have a key as a super parameter in their constructor. The key parameter helps the Flutter engine recognize which widget in a list has changed.
Widget build(BuildContext context)The build method is called when this widget is initialized and inserted into the tree.

Modularity

When your application grows, defining all classes in one file quickly becomes messy. A good convention is to create a separate file for each class (or page).

  • Create a new folder pages in the lib folder
  • In this folder create a new file home.dart
    • This file will contain a new class definition HomePage which returns our earlier created Scaffold with AppBar and Material widget

lib\pages\home.dart

import 'package:flutter/material.dart';

class HomePage extends StatelessWidget {
  const HomePage({super.key});

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Title in App Bar"),
      ),
      body: const Material(
        color: Colors.deepPurple,
        child: Center(
          child: Text(
            "Hello Flutter!",
            textDirection: TextDirection.ltr,
            style: TextStyle(color: Colors.white, fontSize: 36.0),
          ),
        ),
      ),
    );
  }
}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
  • This HomePage widget is
    • a Scaffold widget with an AppBar
    • a Material widget
    • which centers the text Hello Flutter!

lib\main.dart

import 'package:flutter/material.dart';
import './pages/home.dart';

void main() => runApp(const HelloFlutterApp());

class HelloFlutterApp extends StatelessWidget {
  const HelloFlutterApp({super.key});

  
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Hello Flutter App',
      home: HomePage(),
    );
  }
}

 









 

 



codedescription
import './pages/home.dart';imports the home.dart file (and everything that is declared in it)
debugShowCheckedModeBanner: falseremoves the ugly debugger banner
home: HomePage()a HomePage() object is created and placed in the body. The HomePage widget contains a nice page with AppBar and body and will be shown inside the MaterialApp widget.
  • Your app should now look like the image below:
App with widgets

Adding logic

  • Every application needs logic for performing tasks, calling an API, ...
  • Because a widget is a class, you can add logic by writing methods

Methods

  • A method is written in the class
  • Add the following sayHello() method to the HomePage widget:
class HomePage extends StatelessWidget {
  const HomePage({super.key});

  
  Widget build(BuildContext context) {
    return Scaffold(
      ...
    );
  }

  String sayHello() {
    String hello;
    DateTime now = DateTime.now();
    int hour = now.hour;

    if (hour < 12) {
      hello = "Good Morning";
    } else if (hour < 18) {
      hello = "Good Afternoon";
    } else {
      hello = "Good Evening";
    }

    return hello;
  }
}










 




 

 

 






codedescription
String sayHello() { ... }a method named sayHello that returns a string
if, else if, else a conditional if, else if, else statement
  • Call the method instead of showing the hardcoded Hello Flutter! string:
class HomePage extends StatelessWidget {
  const HomePage({super.key});

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Title in App Bar"),
      ),
      body: Material(
        color: Colors.deepPurple,
        child: Center(
          child: Text(
            sayHello(),
            textDirection: TextDirection.ltr,
            style: const TextStyle(color: Colors.white, fontSize: 36.0),
          ),
        ),
      ),
    );
  }

  String sayHello() {
    String hello;
    DateTime now = DateTime.now();
    int hour = now.hour;

    if (hour < 12) {
      hello = "Good Morning";
    } else if (hour < 18) {
      hello = "Good Afternoon";
    } else {
      hello = "Good Evening";
    }

    return hello;
  }
}









 


 
 

 






















  • Since you call the function sayHello(), the Material widget can't be a constant anymore. Don't forget to remove the const keyword.
  • Your app should now look like the image below:
Hello Flutter
  • Well done! You've completed your first Flutter app. Let's try to make the UI a little bit more attractive in the next section