Flutter Basics in 1 Hour | Create your First App [Free]

Flutter Basics in 1 Hour | Create your First App [Free]

Flutter was huge news for Mobile developers in 2018. Started as a simple cross-platform development programming language(IOS & Android will run with one code), it soon started tingling the minds of the community. Took a turn and appeased the Web developers with the launch of the Hummingbird project and now has a road map to create desktop apps as well! (How cool is that).

This article is going to help you take a tour of this programming language(Updated as of November 2019) and get your basics right. If you think already know the basics of native (iOS and Android) development. Where can I learn flutter? This is the article for you. It will ramp you up with what is required in under 1 hour and you can start developing the application easily. That’s right, you need not have any advanced programming knowledge prior to this, this article is enough to Fastrack that for you. All this wants from you is to keep an open mind and the need to learn and by the time the clock ticks 1 hour from now, VOILA! you are ready to start Flutter App development.

There are a lot of things that are moving continuously in Flutter programming language, but the article focuses on the key concepts that will help you Fastrack your learning curve. There are 3 important sections.

First, let us get your environment ready, you definitely need a computer to start programming. Windows, Ubuntu, Mac OS any environment will suffice. Once you got your environment ready(Should not have taken more than 10 minutes), time to learn the Flutter basics. The theory is kept to the minimum and a lot of chances for you to write code down and practice. The final section will pump your adrenaline when you finally have an application in front of your eyes. Ready for this? Let’s complete the flutter basics in 1 hour.

Flutter Basics – Setting up your Environment

Let us start with something very simple, to begin with. The below sections assumes that you already have a computer ready. Choose the below sections based on what your environment is and start the process. Let me meet you again at the end of this section when you have the flutter running!

Setting up Flutter for MAC

If you are planning on developing applications for both Android and IOS, you will be in need of MAC(Since flutter is dependent on XCode to run the iPhone simulator). In case you don’t have a MAC for development, look at Setting up Flutter on Windows/Setting up Flutter on Ubuntu sections below. However, you will not be able to simulate an iPhone experience by any means.

Requirements

To install Flutter in MacOs, you will require the following

  • Disk Space: 700 MB (does not include disk space for IDE/tools).
  • Tools: Flutter depends on these command-line tools being available in your environment.
    • bash
    • curl
    • git 2.x
    • mkdir
    • rm
    • unzip
    • which

All the above command line tools come pre-installed with MacOs. You can go ahead with the following steps if you have the required disk space for the Flutter SDK to reside.

Download Flutter SDK

Download the Flutter SDK from the following location

Flutter SDK Download
Once done, you will find that it is a ZIP folder. UnZip this folder, and copy its path.

You will have to set the environment path variable to point to this Flutter SDK folder by putting the following command into your terminal

Export the path to the Flutter SDK
Export the path to the Flutter SDK

Running Flutter Doctor

Now, the Flutter SDK is in the path. Time to run Flutter Doctor command to check what features are missing. When you run Flutter Doctor. It lists all the dependencies that are currently missing in the system.

Time to install all the required dependencies for IOS and Android development. We will in need of 2 tools. One is XCode which is an IOS native programming Application.

The second is Android Studio which is the Official development kit from Google in order to develop Android Apps. You will require both the Application along with the related dependencies to be in the system to go further.

Install XCode

Time to see how to Install XCode in MacOs. If your system is up to date with the latest release of MacOS, go to the below link.

Option 1

XCode 10

Once the XCode 10 is downloaded, you can give permission for it to be installed in the system. This will install all the XCode and IOS specific dependencies.

Option 2

In case you do not have the latest MacOS. Do not worry(XCode 10 can be downloaded with MacOS Mojave and above only). The Flutter SDK runs pretty much well with any XCode version above 9.0

You can download the older versions from the following link – Developer Tools IOS
You will, first of all, require a Developer Account, which you can create here. Once done, you will have unlimited access to all the developer tools to build, test, deploy anything related to IOS

Once the XCode is installed in your system, run the following command in the terminal. This will let the system know that there is the latest version of XCode present.

sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer

This is the correct command for most of the system. In case you are going through step 2(Installing an older version of XCode), make sure to replace the XCode path with your current path where the XCode gets downloaded.

Setup IOS Simulator on Mac

This step is specific to MacOS only. Since this is not an open source operating system, you need to have a MacOS to develop IOS applications. The IOS simulator gets the same treatment as well. In order to check if the App you built simulates properly on an IOS device, you will require an IOS simulator to be installed.

You can search for the simulator in the MacOS by either checking the spotlight or running the following command in the system.

open -a Simulator

Running that command should pop open the simulator like below.

 

IOS simulator to run Flutter apps
IOS simulator to run Flutter apps

If the XCode is properly installed, this step should run without any issues. If the XCode is not installed properly, remove the XCode and restart the above step from scratch. It is better to not overload the system with unnecessary commands rather than starting everything from scratch.

Setting up Flutter on Windows

Setting up the SDK for Windows is pretty much simple. You do not have any XCode installation to be done. Since windows cannot be used for IOS development. In case you want to simulate the application on IOS, there are 3rd party simulators that are available. This can be used to create and deploy IOS apps. The accuracy, however, cannot be promised.

Let’s look at the requirements and Steps to include Flutter on Windows.

Download the Flutter SDK for Windows

Once the Flutter SDK is downloaded and unzipped. Make sure to place it inside a Folder which does not require permission to access. For (Eg.) Do not place the Flutter folder inside C:>Program files, inside put it inside a folder like C:>src like shown below.

Make sure the flutter folder is inside C:/src and open the environment variable folder
Make sure the flutter folder is inside C:/src and open the environment variable folder

Update your Path to let the Environment know where the Flutter SDK resides. See the below steps to update your PATH variable.

Update the PATH Variable with C:/src/flutter/bin
Update the PATH Variable with C:/src/flutter/bin

Open up the Android Studio and navigate to File>Settings. Find the Plugins option on the left and search for Flutter. You might have to search in all repositories to find it.

Search for Flutter Plugin in Windows
Search for Flutter Plugin in Windows

Once it is found, click install and wait for Download. The Android Studio will require a restart. Perform the restart, and you IDE is ready with the plugin.

Search in all repositories and install the plugin
Search in all repositories and install the plugin

You can find a helpful video which Shows Flutter setup in Windows below

Setting up Flutter on Linux/Ubuntu

Installation in Ubuntu/Linux is similar to that of Mac. You still cannot install XCode or the native IOS simulator since it is restricted to an IOS environment only. The below step illustrates how to install the Flutter SDK to your system

Download the Flutter SDK for Ubuntu

Open a terminal and navigate to the download location. Perform Unzipping of the SDK.

tar xf ~/Downloads/flutter_linux_v1.0.0-stable.tar.xz

Once the bundle is unzipped, time to point the Path to the SDK folder. Use the command below to do that.

export PATH=$PATH:`pwd`/flutter/bin

This will point the path to the Flutter SDK and its files. If you run Flutter Doctor now, it should show all the missing dependencies present.

Common Installations

Install Android Studio

Android Studio plays a major role in terms of developing the Flutter Application. It not only provides the IDE to create the App, but it also provides the required Android Emulator to test the Code in Android devices.

The Android Studio comes packed with required ADB and other related command line tools and does not require any external installation.

To know more about installing Android Studio for Mac/Windows, you can read the Setting up Android Studio for Application development post.

Once you are done, the Studio looks like below.

Opening Android Studio
Opening Android Studio

Open the App and find the preference tab. It is under Android Studio>Preferences

"Preference

Once that is done, you can find the preferences tab with the plugins option on the left section.

Plugins section under preferences
Plugins section under preferences

Search for Flutter. You might have to try searching under Search all repositories to find that. Once done, choose the below option

Choose Flutter under Plugins option
Choose Flutter under Plugins option

Click Install and Restart Android Studio to let the Flutter SDK reflect in the Android Studio IDE.

The restart of the Android Studio now creates a New Tab to create the Flutter Projects. You can find this option in the Android Studio startup or once inside under File>New Flutter Project like below.

Create New Flutter Project
Create New Flutter Project

Test Ride

Time to see if the Flutter Project is working as expected. Continuing from the previous section, go ahead and create a Flutter Project.

The Following section opens up.

Choose from the options
Choose from the options

Choose the Flutter Application option, and the next section asks for the Flutter SDK location.

Remember the first step where the SDK was downloaded and placed in a location. You have to point the project to this location like below.

Flutter Project Details
Flutter Project Details

Once the project is created, you can find the project structure with both the Android and IOS project codebase like below.

Project code base structure for Flutter
Project code base structure for Flutter

Run the project in Your Emulator

Time to take the project for a spin. See what the default project is going to look like. In order to run the project in your environment, you will need to create start the emulators.

To run an Android emulator, do the following.

Navigate to Tools>AVD Manager 

AVD Manager
AVD Manager

Create a new Virtual Device

Create a Virtual Device
Create a Virtual Device
Choose the configuration
Choose the configuration

Once the configuration downloads and the Virtual device builds. It is time to choose the AVD through the Android Studio.

Choose an emulator from the list
Choose an emulator from the list

Upon running the emulator, a new Android-like device opens up. Time to finally run our App on this emulator to see how the device app behaves.

Flutter app
Flutter app

Testing the application on an IOS Simulator looks like,

Iphone app in flutter
Flutter app in IOS Simulator

OK! Did you complete that? Need not have gone through all the setup but is the test application firing in your emulator? If so, all set and done! Time to jump to the next section. It’s going to get really interesting from now on.

Can beginners of programming start with Flutter for app development?

The short answer is yes, the long answer is, you have to spend some time understanding different concepts if you are completely new to Mobile App Programming. This section is targeted for completely new beginners. App Programming basics are always going to be slow, to begin with, and make it difficult if we take off very quickly. However, I have categorized the entire section into very simple sub-sections which will be easy for you to consume.

Note: Even though you need not know the basics of App development, the assumption is that you know the bare-bone basics. For eg, Objects, classes, data-types, etc. 

If you think you are not yet ready with these, highly recommend you take up a 15-minute crash course from here and learn what is happening and how do computers communicate.

Basics of App development

I am listing 3 things for you to keep in mind. I will also be listing down some really important concepts that you can derive from the examples below.

Analyze a Mobile App

Open up your WhatsApp(Picture inset). What do you see? There is a title bar, then a section to show data. Followed by a button to compose new messages. Great!!

What do you think these are? The simplest answer is, all of these are buttons, right? Click a button and something happens in return. Every mobile application is at the heart, broken down into simple clickable(or swipe) actions. Every time the action is registered, the app responds. Put this in your mind and we are ready for the next section.

Understand the Working

Now every mobile application is split into multiple action-packed elements. In flutter, we are going to call these as widgets. Widgets are going to be the most important building blocks that you will have a lot of fun playing with. Widgets can swipe, they can double click, or pinch and do a lot of things in return.

But how do they really do all this? The answer is, you need not know! That’s a very blunt answer but rather an important one. Gone are the days, when every widget was supposed to do something and the developer has to control what and how the things happened. The current trend among the programming paradigm is to leave the working of elements out and rather play with what the elements offer.

This is going to be your second point to remember.

But, I have learned anything related to mobile app development so far, what are you implying? If that is your question, let’s see the next section.

Mobile App Lifecycle

The elements or widget(You will hear a lot of this word in the following sections) is going to do something for the user’s click. But when and what is going to be controlled by the developer. Every App in a mobile environment has a lifecycle. They get created and they get destroyed. Think of this as an example again.

WhatsApp always opens up the first page or the section which contains the chat rather than the other options(Settings, or status page, etc). Why? The answer is, the lifecycle of the WhatsApp gets destroyed as soon as someone kills the app or closes it. This way, the app is born only when it is opened again. That’s the simplest example of a lifecycle in a Mobile Application.

As a developer who is going to build an application, it is important to understand how the Application is going to live in its lifecycle. How do the elements behave during the lifecycle is going to be the only concern for us.

In the subsequent section, we are going to look at the most basic idea about Widgets in Flutter. Widgets in Flutter are the basic building blocks of Mobile App. Without Widgets, we cannot create anything on the UI. Try to understand the points as clearly as possible as the sections following that will be targeting our First Mobile Application for this Course! Excited? Keep going!

Flutter Basics – Understanding Widgets

If you have had experience or even a basic knowledge of Android Application development, you will understand Android’s Views. The flutter’s Widgets are similar to the Views & ViewLayout in Android. However, unlike Android’s Views, the Widget is immutable, meaning you cannot create an object of it or for that matter, it can be modified. You will have to work with the Widget’s state in order to create any type of UI.

For those who do not have any experience in Android, then understand that, Widget’s form the building block for creating a UI. All the components that you see in your phone are made up of multiple widgets and in combination, they become one UI. Widgets are important enough to the lifecycle of the application. Since, they are immutable, meaning they cannot be changed, the Flutter in the background takes care of creating a lightweight Widget tree, every time the UI is changed.

Take an example of swiping right and left in your application. Every time the app is swiped right, the Widget tree is reconstructed. The Widget may be of any one of the following types,

StatelessWidget

A Stateless Widget represents a Widget with no state information. That is, the widget does not hold any information with respect to its previous state, it reconstructs it whenever it needs. StatelessWidgets are useful when the part of the user interface you are describing does not depend on anything other than the configuration information in the object.

For example, in Android, this is similar to placing an  ImageView with your logo. The logo or the properties of the ImageView are not going to change during runtime. Thus, these type of scenarios calls for a StatelessWidget.

There are a lot of other scenarios in which a StatelessWidget can be used, read along to find out more about the Widget Types.

StatefulWidget

If you want to dynamically change the UI based on data received after making an HTTP call or user interaction then you have to work with StatefulWidget and tell the Flutter framework that the widget’s State has been updated so it can update that widget.

An important thing to remember is that both the Type of widgets at the heart rebuild every frame when there is a new Widget tree that is built. The only difference is that the StatefulWidget does the extra role of holding data across frames and restores it whenever required

A combination of Stateful and Stateless widget forms the UI part of the application. There are several scenarios to decide upon the two types of widgets, some of them are,

  1. Choose a Stateless widget when there is a need to hold static or a View that does not react to a change. For (Eg) Logo, Title Text or an Image, etc
  2. Choose a Stateful widget when the widget has to react to change/user interaction. Click on a button should change the Image/Text, then go for a Stateful Widget, since the Text will be dynamically modified on the fly.
  3. Also remember, even if the child is a Stateful Widget, the parent can still be Stateless, if and only if the parent also doesn’t react to change

Writing code for StatelessWidget

Time to see, how we will be writing the first piece of code in Flutter. There are different components when it comes to Flutter’s style of writing code, we will take a look at creating a StatelessWidget in this section.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Android Monks',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: SampleAppPage(),
    );
  }
}

In the first section, we saw above, about the Declarative style of coding. The syntax above follows the same. The class MyApp is going to hold the root of the tree. The StatelessWidget class is the class that we are going to override.

Inside the class, we have the method Widget build(BuildContext context) which will return the Widget object. We will be building the required Widget and return it to the Flutter engine, which then will build the required native code and project it in the Application.

As given above, the MaterialApp is the Widget which we are going to return, there is a variety of Available Widget’s that can be returned, but a basic Application requires the material App Widget. This widget holds a ToolBar and a Body. In order to fill these two attributes, the required ThemeData object is called with the Colors.blue (Meaning, the toolbar is going to be Blue).

If you are an experienced developer, you can visualize or understand what the behind the scenes action will be by the Flutter engine. A beginner, on the other hand, can understand that the above class holds the StatelessWidget, which here is going to be the parent of all the widgets that we will be creating. Since the base app structure is not going to change, the StatelessWidget option seems to be a better fit.

Writing code for StatefulWidget

Since we know what a StatefulWidget will do, we can go ahead and modify the above example code with a StatefulWidget in the home attribute which we have to give.

This will give us a clearer picture of how the Stateless and Stateful widget will act together.

class SampleApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Android Monks',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: SampleAppPage(),
    );
  }
}

class SampleAppPage extends StatefulWidget {
  SampleAppPage({Key key}) : super(key: key);

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

class _SampleAppPageState extends State<SampleAppPage> {
  // Default placeholder text
  String textToShow = "Android Monks Example";

  void _updateText() {
    setState(() {
      textToShow = "Text Changed";
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Stateful widget"),
      ),
      body: Center(child: Text(textToShow)),
      floatingActionButton: FloatingActionButton(
        onPressed: _updateText,
        tooltip: 'Update Text',
        child: Icon(Icons.update),
      ),
    );
  }
}

There are a lot of components in the above code, we will try to break it down to understand the entire idea of a StatefulWidget.

  1. The root of the UI is a StatelessWidget as shown in the above section. The home attribute, however, is making a call to another class called SampleAppPage. This class extends the StatefulWidget.
  2. The first thing we do as soon as the StatefulWidget is inherited is to create a constructor for that class. This is similar to the onCreate() method in our activity, where we pass the bundle back to the superclass. In understandable terms, the class which we are inheriting has to know about the child class. Thus we create a constructor for that class and call the super method on it. This will let the StatefulWidget class (And eventually the Flutter engine) know about the component which is in need of a StatefulWidget
  3. In the StatefulWidget section, we learned that the only difference between a stateless and a stateful widget is in the function call of the setState() which will restore the state information that the widget holds. In order to give that call, the createState() method has to be overridden
  4. Coming on to the use of _SampleAppPageState. This is where the main logic is going to be written. The class extends the State of the SampleAppPage (which is now a stateful widget holding various state information). 
  5. Override the build method with the required Widget type(We saw MaterialApp in the stateless widget, here it is going to be a Scaffold). There can be any number of widgets added inside this.
  6. The floatingActionButton attribute is then created with the required property. The ToolTip specifies the name on the ActionButton. The main attribute to look at is the onPressed
  7. The onPressed is making a call to the helper method that we have defined locally. All it does it, it calls the setState() method every time the button is clicked.
  8. The setState() method, in turn, changes the textToShow variable to what we require. The widget is reloaded, and the new text appears.

This is how the entire flow of the basic layout of the Flutter app works. For a beginner app developer, this will be very easy to pick up, since the flow is linear.

Building the First Flutter Application

If you have reached this section, that means you are on track to complete this course and launch your application. With Flutter application, it is important to understand that there are a lot of things that keep changing. Additionally, newer widgets come in all the time. We will take a look at few important widgets that are absolutely required(Like the Scaffold Widget in the previous section) and finalize on what is absolutely required to build our first running Mobile Application.

This section will help you in building your first Image Toggle Application. What the application is going to do is that it will try to swap images continuously every time a button is clicked. (Think of it as a Tinder Clone) and when you like a picture, click on the Like or Connect button to Show you information about that image!

So let’s get the ball rolling to achieve this Application in our final section.

Flutter Tutorial Complete – Create a new Project

Start with a fresh and name it as TinderClone! Once you go through the entire flow of the application, this is how the app project is going to look like. Note: You can either use a Visual Studio Code IDE or Android Studio IDE for this project.

Once the IDE is fired up and we are ready to start the application from scratch. Do not copy-paste the code into the browser as it will become really hard to understand what exactly is happening.

There are 2 parts to this application.

  1. The first part involves creating the basic layout for us to build on top of. Beginning with a simple application that will be bare bones.
  2. Once the application works, we will take that and add a styling option and a lot more to it.

The below code is the final Flutter Code that will trigger the entire application. Find the explanation for each line of code below. (Note: It is really difficult to explain every single line of code in the form of text, highly recommend watching the video for much clearer understanding)

Flutter Tinder Clone Example App – Step By Step explanation

  1. Beginning with the void main(), this is the entry point for the application. Every Flutter application is going to have the Void main() in any one file. The Flutter is smart enough to detect which file has the main() call and starts the application from that point.
  2. The main() method now has to call the runApp() method, which is important to trigger the application. Think of this as creating an outer structure to lay the app on top of it.
  3. Coming to the first important Widget. MaterialApp widget is a very important widget that will create the base layout for application to start stacking its different widgets.

With this, the application enters an important part of showing something valuable on the Screen. As discussed in the previous section, there are two types of widgets, Stateful, and Stateless widgets. In this example application, we are dependent on the Stateful Widget for one important reason. Stateful widgets are very important to help in triggering a UI change. Period!

Stateful widgets can only trigger a change to the UI while Stateless widgets are nothing but simple place holders.

The Stateful widget is used as our important Widget here. We have named it SampleApp and the following are the important actions that are performed inside it.

  1. Store a bunch of images on the UI, and change it every time the person tries to click Swipe Right.
  2. We will replace it with 2 buttons. One is a Swipe Right button and the other is to swipe left.
  3. These two buttons will have different actions but both call the setState() method.

With the above steps, check out the following code and how it is arranged. The most important widget that will assist us in creating a simple UI very fast is the Scaffold Widget in Flutter. Very handy and at the same time easy to create a UI with this one Widget.

import 'package:flutter/material.dart';

void main()
{
  runApp(
    MaterialApp(
      home: SampleApp(),
    )
  );
}

class SampleApp extends StatefulWidget {
  @override
  _SampleAppState createState() => _SampleAppState();
}

class _SampleAppState extends State<SampleApp> {
  int position = 0;
  String successMsg = "";

  @override
  Widget build(BuildContext context) {
    List<String> imageConst = [
    "https://images.pexels.com/photos/712877/pexels-photo-712877.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
      "https://images.pexels.com/photos/1662639/pexels-photo-1662639.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
      "https://images.pexels.com/photos/1248488/pexels-photo-1248488.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"
    ];

    return Scaffold(
      appBar: AppBar(
        title: Text("TINDER CLONE"),
      ),
      body: Container(
        child: Column(
          children: <Widget>[
            Center(
              child:
              Image.network(imageConst[position],
                  width: 300.0,
                  height: 300.0
              ),
            ),
            FlatButton(
              child: Text("Swipe Right",
                style: TextStyle(fontSize: 25.0, fontWeight: FontWeight.bold, color: Colors.white),),
              color: Colors.blueAccent,
              onPressed: (){
              this.setState((){
                successMsg = "You have matched!";
              });

              },
            ),
            FlatButton(
              child: Text("Swipe Left",
                style: TextStyle(fontSize: 25.0, fontWeight: FontWeight.bold, color: Colors.white),),
              color: Colors.blueAccent,
              onPressed: (){
                this.setState((){
                  if(position == 2)
                    {
                      position = 0;
                    }
                  else{
                    position +=1;
                  }
                });
              },
            ),
            Text(successMsg,
            style: TextStyle(fontSize: 40.0, fontWeight: FontWeight.bold),)
          ],
        ),
      ),
    );
  }
}

With the code running, the following application is going to be generated!

Simple Flutter Tinder Clone App
Simple Flutter Tinder Clone App

Flutter Basics in 1 Hour – Conclusion

Time to look at what the application is, and what we learned throughout this article. It is highly recommended to take a look at the video embedded above for a much clearer understanding. However, if you prefer the article, bookmark this URL to come back at a later point.

Can Flutter be learned easily?

Yes, Flutter is newer in the application development domain and also has a growing community of developers who are using this actively. All you have to do is read through this article to understand all the basics in just 1 hour and start building applications to create bigger and better applications.

Leave a Comment

Your email address will not be published. Required fields are marked *