0% found this document useful (0 votes)
763 views28 pages

(Guide) MY FIRST SMARTPHONE APP WITH FLUTTER

This document provides instructions for creating a simple miles to kilometers conversion app using Flutter and Dart as a first mobile app project for beginners. The app will display a text field to enter miles and a button to convert and display the result in kilometers. The document explains what Flutter is, its advantages, and step-by-step instructions to set up the development environment including Android Studio, Flutter, and Dart. It then guides the reader through creating a new Flutter project and connecting their Android device for debugging.

Uploaded by

Kiptoo Nickson
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
763 views28 pages

(Guide) MY FIRST SMARTPHONE APP WITH FLUTTER

This document provides instructions for creating a simple miles to kilometers conversion app using Flutter and Dart as a first mobile app project for beginners. The app will display a text field to enter miles and a button to convert and display the result in kilometers. The document explains what Flutter is, its advantages, and step-by-step instructions to set up the development environment including Android Studio, Flutter, and Dart. It then guides the reader through creating a new Flutter project and connecting their Android device for debugging.

Uploaded by

Kiptoo Nickson
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

MY FIRST

SMARTPHONE
APP WITH
Kipkoech Rodge

FLUTTER
Follow this simple guide to develop a fully functional Android app that runs on
your phone today. This is a simplified guide for absolute beginners to
programming but with the desire to acquire professional-level skills in mobile
app development.
Introduction
Almost everyone today relies on a smartphone to lead a smoother, more convenient life. It is
important now more than ever that you learn to create applications that you can use on your device.
I am a self-taught programmer, and I guarantee you that if you have the will, the time, and a basic
technological know-how on how computers work, you will be able to create an app you can use on
your Android smartphone or iPhone, or tablet by the end of this guide

What you will create


This course is designed for absolute beginners to programming. Whether you have basic knowledge
in Object-Oriented Programming languages (OOP) such as Python, Java, or C++ or just know how to
type out a document in Microsoft Word, the broader course this brief guide is based on aims to turn
you into a career mobile app developer in no time.
At the end of this brief introduction you should have created a practical application that converts
miles into kilometers. We will call it miles2km and it will look like this:

Screenshot of the app we will create in this introduction.


What you will learn
There is no easier way to create an application for your Android or iOS device than with Google’s
brand new app development framework called Flutter. Version 1.0 of Flutter was just released in
December 2018 but it had been in beta for quite a while prior. This app development platform runs
on the Dart programming language, a new and easy to learn but powerful Object-Oriented
Programming language currently on version 2. Should you choose to pursue this course, you will
learn to create applications for everywhere – including the web, Dart VM, and even JavaScript – with
Dart. Rather than learn one of the many variants of JavaScript languages out there, just learn Dart,
which can be compiled to JS with ease.

What is Flutter?
Flutter is the newest mobile application Software Development Kit (SDK) that designers and
developers can use to build modern apps for Android and iOS. Flutter, just like Dart, is an open-source
framework maintained by Google and other big players in the tech world. It works with a ton of other
mobile app SDKs and development tools including Firebase. Flutter was created mainly to simplify
the app development process and to create beautiful user interfaces with smooth scrolling, rich
motion, and highly customizable components.

Why Flutter?
1. Flutter is an open-source project that is easy to learn and use.
2. There is no better opportunity to learn Dart programming language than through mobile app
development.
3. The app you will build with Flutter is almost indistinguishable from another built with traditional
Android SDK.
4. Flutter makes it possible to build apps for both Android and iOS systems from a single code base.
5. Your app will run much more smoothly and have a vibrant refined appearance.
6. Dart is fast and comes with a ton of great features including optional static types, isolates, mixins,
and generics that make it easier to create apps.
7. The UI components in flutter are all Widgets that are easy to master and manipulate.
8. Flutter widgets are rendered by an engine in real-time. It is much more exciting to develop apps
when you can see progress the moment you save your code.
9. All the UI elements conform to the Material Design guidelines out-of-the-box.
10. Flutter has a vibrant and fast-growing community and enthusiasts.

Prerequisites
To follow this guide and create the miles2km app with Flutter, you will need:
1. A computer running Windows, Linux, or Mac. This brief guide will focus on Windows.
2. Android Studio 2.2 or newer. Later you can use IntelliJ IDEA or MS Visual Code if you prefer.
3. Android smartphone running version 4.4 or newer with USB cable (later you can use an
emulator on your computer instead).
Installing Flutter, Dart and Android Studio on Windows 10
The most straightforward way to install Flutter SDK is with Android Studio.
Step 1: On your browser, go to https://developer.android.com/studio/ and download Android
Studio. Note that the installation file is larger than 1GB. It may take a bit of time if you are using a
slow connection. Install when download is complete.
Step 2: Go to https://git-scm.com/download/win and download Git for Windows. Install when
download is complete. Make sure that the ‘Use Git from the Windows Command Prompt’ option is
checked during installation.
Step 3: Open command prompt. Go to Start > Windows System > Command Prompt or type Run
in Search and press Enter.
Step 4: Download and set up the Flutter SDK from GitHub. Navigate to the folder into which you wish
to download and install Flutter (e.g. C:\Flutter) then open the terminal window on your computer
and enter this command:

git clone https://github.com/flutter/flutter.git

The Flutter SDK will be downloaded into the working directory from which you executed the
command.
Step 5: Open the Flutter directory and find the flutter_console.bat file and open it by double-clicking.
Flutter requires a number of dependencies including Material Design fonts and Dart SDK and to run.
Luckily, these are downloaded and installed automatically the first time you run the flutter diagnostic
tool.
On the Flutter console, run the command:

flutter doctor.

Step 6: Next, set up environmental variables or PATH. This step is necessary to run Flutter commands
right from your Windows terminal. To set up PATH for the current user, go to Search and type ‘PATH’
or ‘env’ then click on ‘Edit system environmental variables.
Under System variables, there is a row named ‘Path’. Click on it and click on the ‘Edit’ button at its
bottom. The ‘Edit environmental variable’ window will open.
Click ‘New’ and add the path to the bin sub-directory of your Flutter install location. For instance, in
my case, it is C:\Flutter, that is why I set up C:\Flutter\bin in PATH. Click OK to save and close the
windows.
To check that Flutter PATH is set up correctly, open a new instance of your terminal and type the
command: flutter or run Flutter doctor with the command ‘flutter doctor’.
Step 7: Restart Windows to fully apply system changes.
Step 8: Finally, to build Android apps in Flutter, you must point the SDK to the Android Studio
directory. First, accept licenses by typing the following command on your terminal:

flutter doctor --android licenses

The Android toolchain item in the list should be checked [✓] when you run Flutter doctor before
you can proceed.
If you cannot see the check next to Android toolchain there should be a suggestion the output on
what you need to do to install whatever is missing or accept any agreements before you can proceed.
To be able to build Android apps, you must also point Flutter to the directory where you installed
Android Studio.
Step 9: Configure Android Studio. Start by opening it from the Start menu. On the welcome screen,
click Configure > Plugins. Search for Flutter and click Install to install.

Since Flutter runs on Dart, you will be prompted to install its plugin as well. Accept and install. Once
both plugins are installed, you will be asked to restart Android Studio for changes to take effect. On
the welcome screen, you should now see the option to start a new Flutter Project that was not there
before.
You are now ready to create an Android or iOS app with Flutter and Dart in Android Studio.
Building your first app
Click on Start a new Flutter project. You will get a New Flutter Project window shown below. Click
on the first option ‘Flutter Application’ and click Next.

In the next screen, configure your new app. Give it a project name, beginning with a lowercase letter.
In our case, we will call it miles2km. You may also need to specify the installation directory of your
Flutter SDK.
Choose a location to create your app and give it a brief description. Check ‘Create project offline’
then click Next.
In the next screen, enter a simple domain e.g. ok.ke. We will learn about this later.
Click Finish and wait for Android Studio to create your project.
Next, enable USB Debugging mode on your smartphone and connect it to your computer. To enable
debugging mode, go to your device Settings and scroll down to ‘About phone’, tap on it, and in the
next screen scroll down to ‘Build number’. Tap it seven times (it will count down for you) to enable
Developer options. When done, you will see a toast ‘You are now a developer!’.
Go back to Settings. At the bottom, there will be a new Developer options item in the list. Tap it and
in the new window find USB Debugging and enable it.

WARNING!
When enabled, USB Debugging grants the user high-level access to an Android device. In the
wrong hands, this is a grave security risk. Therefore, it is recommended that you disable it when
you do not need it. This is particularly important if you are worried of hackers or USB-contracted
malware. Luckily, you only need to uncheck the USB debugging mode from the Developer options
when you do not need it, no need to enable Developer options again.
Run Flutter doctor on the terminal or from the Android Studio terminal to ensure that your device is
ready to run our miles2km app.

If all the items are checked green, go to Android Studio and verify that your device is visible. Click the
green Run icon to run your app.

Note that a new project generated on Flutter has a basic but functional structure of an app. Every
new project features a ‘Flutter Demo’ app that looks like this when run:
Once the demo code runs on your device, you will not need to press the Run button again after
modifying the program’s code. Flutter features ‘hot reload’ which instantly updates the app when
you save the code. However, you may need to hot restart the app if you make changes that demand
refreshing of stateless widgets in the app, loading new classes or functions, or affects the material
design of the app (do not worry, we will learn about all this).
Our project has a single file called main.dart. As you may have guessed, the file is created in the Dart
programming language we mentioned earlier. Select all the code in the file by pressing Ctrl+A on
your keyboard and press ‘Delete’. We will write our app from scratch.
What happens on your app when you save an empty Dart file?

Creating Widgets
Our application is very simple. Here is a simple pseudocode of the app should do:
1. App starts
2. User enters the distance in miles.
3. User taps button for the app to convert value to kilometers.
4. App displays the result in kilometers.
5. App stops
It is always a good practice to write a pseudocode of the app you wish to create to structure the flow
of the program. Here is a flowchart of our miles2km app.
START

MILES

CONVERT

KM

STOP

We do not need to write any code to start and stop the program in our app. Therefore, we will need
to create the following widgets:
1. A TextField that will accept the distance in miles (a number).
2. A RaisedButton to convert the value using a formula.
3. A Text widget to display the result.
There are two types of widgets in Flutter: StatefulWidget and StatelessWidget. As their names
suggest, these widgets are different in that the former has a State while the latter doesn’t.
A StatefulWidget is associated with a State object, which allows the widget to react to changes in the
data contained in the Widget. A StatelessWidget, in contrast, is a much simpler object that does not
store persistent data i.e. data whose status (State) is not expected to change during the running of
the app.

App entry point


On the first line of the main.dart file open in Android Studio, let us first import the package that
makes it possible to create widgets in Flutter. Enter the following code (ignore the number preceding
the import keyword. This number will guide you as you follow this guide):
1 import ‘package:flutter/material.dart’;

The ‘material.dart’ package is a library of all the Material Design widgets that your app will use. This
package must be imported in every dart file you create in the project. The Dart file requires a main()
function to run, therefore we will add its code next and call the runApp() function to initialize the
application. Here is the code to write:

1 import ‘package:flutter/material.dart’;
2
3 void main() => runApp(Miles2KM());

We have pointed the main function to run an app called Miles2KM, but we have not created the app
yet. Next, we will create the app class to extend a StatelessWidget that will be built when the app is
initialized. Here is the code:

3 void main() => runApp(Miles2KM());


4
5 class Miles2KM extends StatelessWidget {
6 @override
7 Widget build(BuildContext context) {
8 return MaterialApp();
9 }
10 }

You can see in the code that we defined a class called Miles2KM that extends a StatelessWidget, which
overrides a widget build function. The widget build essentially involves creating a material
application that is empty so far. We now have the bare bones of our app.
Before we can run our app, we need to give it a StatefulWidget, or the dashboard on which the user
works on. Remember that a StatefulWidget has contents that change, and as such, is required if an
app is to be functional. Add an empty line after the previous and insert a StatefulWidget the easy way
by typing stful then press Enter.
How this code works is not the most important thing for you to understand at this point. It is pretty
straightforward though, especially if you are familiar with object-oriented programming. You can see
that the widget Dash class extends a StatefulWidget with another _DashState class. Remember there
was no state defined in the StatelessWidget we created earlier. You should also notice that this widget
builds and returns a Container and not a MaterialApp. Your code should look like this at this point:

1 import ‘package:flutter/material.dart’;
2
3 void main() => runApp(Miles2KM());
4
5 class Miles2KM extends StatelessWidget {
6 @override
7 Widget build(BuildContext context) {
8 return MaterialApp();
9 }
10 }
11
12 class Dash extends StatefulWidget {
13 @override
14 _DashState createState() => _DashState();
15 }
16
17 class _DashState extends State<Dash> {
18 @override
19 Widget build(BuildContext context) {
20 return Container();
21 }
22 }
23

Our app still cannot run, but this is only because we have not pointed the main app StatelessWidget
to the StatefulWidget we just created. To do this, we will point the MaterialApp to the Dash class by
defining the latter as the home in the Material app. Here is how:
8 return MaterialApp(
9 home: Dash(),
10 );
11 }
12 }
13

When you save your app, it should hot reload and something will finally happen on your device.
Technically, we have a functional app, but it does nothing so far.

Creating the user interface


We have our app ready, but it has nothing to display. This is because we have not built the interface.
While creating the Dash widget, Flutter returned a Container by default. However, this is not the
widget we need to use to create the rest of the app. Therefore, we will change it to a Scaffold. Do not
worry about the what or why, we will cover this later. Modify the StatefulWidget to make it return a
Scaffold instead of a Container by simply replacing the Container keyword with the keyword
Scaffold, like this:

21 Widget build(BuildContext context) {


22 return Scaffold();
23 }

What happens when you save the code? It should hot reload with something to display.

Adding the app bar


One of the core elements of Material Design UI is an app bar. With a Scaffold, it is very easy to create
an app bar and to establish a relationship between it and other UI elements in the app. Define an app
bar within the Scaffold like this:

22 return Scaffold(
23 appBar: AppBar(),
24 );
25 }

When you save your code, an app bar with a blue background should appear on your app. However,
we do not want it blue, and neither do we want it blank. We will add two properties: a title and
background color using the keywords title and backgroundColor respectively. Here is the code:
23 appBar: AppBar(
24 title: Text(“Convert Miles to Kilometers”),
25 backgroundColor: Colors.pink);
26 ),//AppBar

What happens when you save your app? I used color pink in this guide but of course you can choose
one from the many other color options suggested when you start typing.

Creating app body


Next, we have to create a body for our app. The body is where the important widgets that the user
interacts with are placed. We will create a body and assign it a Container widget so that we can add
more widgets. Get out of the AppBar and add this code to your Scaffold:

26 ),//AppBar
27 body: Container(
28 child: Column(
29 children: <Widget>[]
30 ),// Column
31 ),// Container

We already learnt that in Flutter, all material design elements are widgets. Some parent widgets, such
as Container, can accommodate only one widget called a child while others such as Column, Stack,
and Row can accommodate multiple widgets called children. Widgets that accommodate more than
one widget are referred to as layout widgets.
Because our app has three main widgets – a TextField, a RaisedButton, and a Text arranged vertically
one after another, we will use a Column. A Column widget will require a children property to create
a widget that holds all the other widgets we will create. We would use a Row widget if we wanted to
arrange one widget next to another (horizontally).
Create the TextField, RaisedButton, and Text widgets inside the Column widget like this:

29 children: <Widget>[
30 TextField(
31 decoration: InputDecoration(labelText: “Miles:”),
32 ),// TextField
33 RaisedButton(
34 child: Text(“Convert”),
35 onPressed: () {},
36 ),// RaisedButton
37 Text(“Result”)
38 ]//Widget

Notice that the three widgets are placed inside square brackets ([ ]) and are separated by commas.
The RaisedButton requires an onPressed() function, which in this case we left blank. This is where
we will call the function to convert milesVal to kmVal by multiplying the former by formulaVal.
Widget tree
An app built in Flutter is essentially a tree of widgets. Our miles2km app is an arrangement of
widgets forming parent-child relationships. If you are having difficulty visualizing it, our app at this
point looks like this:

Scaffold

AppBar Container

Text Column

TextField RaisedButton Text

Text

If you open the Flutter Inspector on the right side of your Android Studio IDE you will be able to see
just how the app is structured.
Declaring variables
Every computer program uses variables to store the data it processes. In order for our app to accept
input, process it, and give out a result, we must create named spaces in memory where the data used
will be stored. These named spaces are called variables.
Our application needs to have three variables:
1. Space in memory to hold the value of miles the user enters. This value will be a double
because we expect it to be a number with a decimal point. We will call it milesVal.
2. Space in memory to hold our conversion formula of 1.6. This is what we will multiply the
milesVal with to get the kmVal. Since we do not expect this value to change during the
execution of the program, we will declare it as final. Let’s call it formulaVal.
3. Space in memory to hold the result. This will also be a decimal number. We will call it kmVal.
Scroll up to _DashState class declaration and add these variable declarations within the class:

19 class _DashState extends State<Dash> {


20 var milesVal = 1.0;
21 final formulaVal = 1.6;
22 var kmVal;
23

One of the best features of Flutter is that you do not need to explicitly declare the types of all variables
when defining them. In our case, by assigning the milesVal and formulaVal initial double values
automatically assigns them the corresponding data type. You can also see that we did not assign the
kmVal an initial value and neither did we declare the type of data it should hold. When a variable
does not have a specific data type assigned to it, it is known as a dynamic type.

Fetching values from a TextField


In Flutter, a value cannot be fetched directly from a TextField. We will need to use a controller, in this
case a TextEditingControlle, to get the text data from the input field. Just below the variable
declarations, create the TextEditingController called controller1 like this:

24 final TextEditingController controller1 =


TextEditingController(text: "");
25

The argument passed when creating the TextEditingController (between the brackets) is the default
value. Next, we will make the controller get the value from the TextField by giving it a new controller
property with the value of the controller name, like this:
36 TextField(
37 decoration: InputDecoration(labelText: "Miles:"),
38 controller: controller1,
39 ),// TextField

Data captured in the TextField is of type String by default.

Processing fetched data


Now that we have a controller to fetch the milesVal, we now need to create a way for the captured
data to be converted to the right format (double) before we can carry out any calculation. To do this,
we will create a function doConversion that parses the text data fetched by the controller into type
double, then multiply the result with the formulaVal to return kmVal. Here is the code that does this:

25
26 void doConversion() {
27 setState(() {
28 milesVal = double.parse(controller1.text);
29 kmVal = milesVal * formulaVal;
30 });
31 }

Our app is almost complete. Now we need to write the code to call the doConversion method to
process the readied variables. This is what the “Convert” RaisedButton is for. Go to its onPressed:
property and modify it as such:

47 RaisedButton(
48 child: Text(“Convert”),
49 onPressed: () {
50 doConversion();
51 }

Finally, for our app to work, we need a way to view the result of the doConversion process. We are
going to pass the output of the process on to the last Text widget in our Column. Here is the code:

53 Text(“$milesVal miles is about to $kmVal Kilometers”)

Reload the application and try it out. Does it look like I promised it would at the start of this course?
You have now created a fully functional program that runs on your smartphone using Flutter with
little effort – and it is just over 50 lines of code!
Improving the miles2km app
What you have created is possibly one of the dullest apps ever. There is a lot we can do to improve
the appearance and the functionality of the app though, but it was important I keep this introduction
as concise as possible. With a little tweaking of the widgets we used in this app, you will improve the
app enough to impress anyone. Here are five basic improvements you can make to improve the app:

1. Place the app at the center of the screen


Give the column a new property to align its children along the main axis. Add a new line of code just
under ‘child: Column(‘ like this:

42 child: Column(
43 mainAxisAlignment: MainAxisAlignment.center,
44 children: <Widget>[

The default value for the mainAxisAlignment property when not specified, is
MainAxisAlignment.start. You can also try out other alignment options including
MainAxisAlignment.end and MainAxisAlignment.spaceBetween, MainAxisAlignment.spaceAround,
and MainAxisAlignment.spaceEvenly to see what each does.

2. Increase font size of the TextField


Add another property to the InputDecoration widget called ‘labelStyle’. Go to the end of labelText:
“Miles:” property and add this code:

46 labelText: "Miles:", labelStyle: TextStyle(fontSize: 30.0)),

We formatted the labelStyle as Text by assigning it a new property of fontSize with the value 30.0.
Note that the value is a double value, not an integer (30). You can also add more properties such as
fontWeight for bold) and fontStyle (for italic) etc.
To do the same for the input text, apply the same style property to the TextField widget as you did
the labelText, like this:

48 style: TextStyle(fontSize: 30.0, color: Colors.green),

Can you apply the same style to the Text widget at the bottom of our column?

3. Restrict keyboard to numbers


Since the input of our app is strictly numeric, it makes more sense to only call up number keys of the
keyboard when the TextField is in focus. Give it a new property called keyboardType and assign it
value TextInputType.number, like this:
49 keyboardType: TextInputType.number,

Save the app to hot reload it. Tap on the TextField. See any differences in the keyboard? If the changes
are not reflected, you may have to hot restart it.

4. Add spaces between widgets


Add a new SizedBox widget between the TextField and the RaisedButton widgets then give it a
height: property with a double number value such as 20.0.

49 ),//TextField
50 SizedBox(height: 20.0),
51 RaisedButton(

Copy the SizedBox widget and paste it between the RaisedButton widget and the Text widget. Feel
free to change its height value as you see fit.

57 ),//RaisedButton
58 SizedBox(height: 50.0),
59 Text(

Your app should be getting more presentable at this point.

5. Add padding to the Container widget


Click on the Container widget name. You should see a lightbulb icon appear to the left of the line of
code. When you hover over it, a dropdown arrow will appear. Click on it and click on ‘Add padding’.

The padding widget will become the new parent to the Container and a new padding property with
a constant value of EdgeInsets.all(8.0) added. Try changing the double value from 8.0 to something
like 30.0 and see what happens.
Bonus: Center the AppBar title and Remove the DEBUG banner on the top right corner
Add a new centerTitle: property to the AppBar, just below the backgroundColor, like this:

38 backgroundColor: Colors.pink,
39 centerTitle: true,
40 ),

Go to the MaterialApp inside the StatelessWidget and give it another


debugShowCheckedModeBanner property with a value false.

8 return MaterialApp(
9 debugShowCheckedModeBanner: false,
10 home: Dash(),

The centerTitle and debugShowCheckedModeBanner properties take Boolean types of data, known
as bool in Dart. This data type returns either true or false.
Here is how your app should look like:
What Next?
I designed this introductory guide as a way to show absolute newbies that anyone, with ambition and
dedication, can become an app developer with little effort. I have created a complete course that takes
you from zero to flutter and dart hero in a very short time. If you completed building the miles2km
app, whether or not you understand what a widget in Flutter is, I guarantee that you can become a
professional app developer if you really want to.
My course is not only comprehensive – taking you through the beginner-intermediate-advanced
stages of learning, but also practical and personalized. I have made it a priority to create a course that
will keep you interested in learning through every stage as you create killer apps that you will be
using on your device in your everyday life.
Check out my course content on https://code.ok.ke.
The Code
Here is the complete code of the miles2km app without improvements discussed in the last section
of the guide.
import 'package:flutter/material.dart';

void main() => runApp(Miles2KM());

class Miles2KM extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
home: Dash(),
);
}
}

class Dash extends StatefulWidget {


@override
_DashState createState() => _DashState();
}

class _DashState extends State<Dash> {


var milesVal = 1.0;
final formulaVal = 1.6;
var kmVal;

final TextEditingController controller1 = TextEditingController(text:


"");

void doConversion() {
setState(() {
milesVal = double.parse(controller1.text);
kmVal = milesVal * formulaVal;
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Convert Miles to Kilometers"),
backgroundColor: Colors.pink,
),
body: Container(
child: Column(
children: <Widget>[
TextField(
decoration: InputDecoration(labelText: "Miles:"),
controller: controller1,
),
RaisedButton(
child: Text("Convert"),
onPressed: () {
doConversion();
},
),
Text("$milesVal miles is about to $kmVal Kilometers")
],
),
),
);
}
}

You might also like