Flutter Getting Started: Tutorial 1 Basics – DEVELOPPARADISE
17/07/2018

Flutter Getting Started: Tutorial 1 Basics

Introduction

Howdy! That’s what my Architect says, whenever he starts the daily scrum. I am saying the same as I am writing an article after a long time. That’s a shortcoming from my side as I haven’t learnt anything new or worth sharing for a long time now! All those years, I am shamelessly taking inspiration from others, without contributing much.

Last time I wrote articles in Xamarin (when they were independent software, not bought by MS), and at that time Mr Joseph Hill was kind enough to share a free licence with me. Though after coding in it for some time, as I am mainly focused on Andorid Platform, I find writing code in C# cumbersome, as internally it’s compiling code to Java and code construct is similar to that of Java (like Event Handler, etc.), where I never felt at home. Slowly, I lost charm for it and completely abandoned learning mobile platform.

However, recently, I found out a really cool cross platform mobile development tool written by Google, which is Flutter, though still in beta stage, however I believe it has a bright future. Also, language for development is Dart, which I am glad is closer to C++/C# and much easier to learn in comparison to other languages and it’s open source and actively developed. Though Xamarin mobile development kit is free now with VS2017 community edition.

Background

I am quoting this from this link, Written By Mr. Wm Leler:

Quote:

“The fact that Flutter is the only mobile SDK that provides reactive views without requiring a JavaScript bridge should be enough to make Flutter interesting and worth trying, but there is something far more revolutionary about Flutter, and that is how it implements widgets”

This image would let you know how Flutter renders application natively, taken from the same link as above:

Flutter Getting Started: Tutorial 1 Basics

Why Flutter uses Dart

Instead of repeating myself, I am quoting from this link, Written by Mr. Wm Leler

  • Dart is AOT (Ahead Of Time) compiled to fast, predictable, native code, which allows almost all of Flutter to be written in Dart. This not only makes Flutter fast, virtually everything (including all the widgets) can be customized.
  • Dart can also be JIT (Just In Time) compiled for exceptionally fast development cycles and game-changing workflow (including Flutter’s popular sub-second stateful hot reload).
  • Dart makes it easier to create smooth animations and transitions that run at 60fps. Dart can do object allocation and garbage collection without locks. And like JavaScript, Dart avoids pre-emptive scheduling and shared memory (and thus locks). Because Flutter apps are compiled to native code, they do not require a slow bridge between realms (e.g., JavaScript to native). They also start up much faster.
  • Dart allows Flutter to avoid the need for a separate declarative layout language like JSX or XML, or separate visual interface builders, because Dart’s declarative, programmatic layout is easy to read and visualize. And with all the layout in one language and in one place, it is easy for Flutter to provide advanced tooling that makes layout a snap.
  • Developers have found that Dart is particularly easy to learn because it has features that are familiar to users of both static and dynamic languages.

Anyways let’s get started, I would be posting separate tutorials for Dart language as tips and tricks ASAP, I have posted first article in this series, please click here to access first. Following tools are required to actually build and these tutorials:

Though you can use Visual Studio code instead of Android Studio, I insist on installing Android Studio, as now visual Android SDK is coming as part of the same, it would be medium level difficulty to install SDK from the command line. At least, a big NO for beginners.

Using the Code

I would be doing the following stuff in this tutorial, I am concentrating only on StatelessWidget:

  • Task#1: Creating a page with AppBar showing title
  • Task#2: Putting Raised Button in the middle of the page and onClick raising Snackbar
  • Task#3: Putting bottom bar with Icon Buttons, responding to click

As usual, like all of my other articles, I am assuming that the person reading this article is a novice and I would start step by step:

  1. Open Android Studio and configure Flutter and Dart SDK/Plugin like this, you have to click on File->Settings and select plugins to open this page

    Flutter Getting Started: Tutorial 1 Basics

    In case you don’t see it installed, please press on Browse repositories button and search for Flutter plugin, it will install Dart plugin with it.

  2. Now create new Flutter project, and name it tutorial1, please mind the name of project is always in lower case, press next to set package name and then finally complete it.

    Flutter Getting Started: Tutorial 1 Basics

     

    Flutter Getting Started: Tutorial 1 Basics

  3. Delete all the boiler plate code, which is written as part of project creation, your main.dart file which is lib folder should look like this:
    import 'package:flutter/material.dart';
    import 'package:tutorial1/myhomepage.dart';
    
    void main() => runApp(new MyApp());
    
    class MyApp extends StatelessWidget {
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        return new MaterialApp(
          title: 'Flutter Demo',
          theme: new ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: new MyHomePage(title: 'Flutter Tutorial #1'),
        );
      }
    }

    Let me explain what is happening in this code.

    • Entry point for Flutter/Dart project is main(), so we are using short code for RunApp by passing object of MyApp, which acts as base class for our tutorial, you can name it anything of your choice, till the time it is conforming with Dart Class declaration format
    • The MyApp Class extends StatelessWidget (a widget that does not require mutable state)
    • We would override build method and return MaterialApp, where in home property I am providing MyHomePage object, which will act as main class for page display
    • Flutter uses Material Design, to provide similar look on across platform

    Yes Editor would be showing error as we haven’t created the MyHomePage yet, we will create the same in the next step.

  4. Right click on lib folder and hover on new item to create new Dart File, name it as myhomepage.dart, you just need to type filename, it will automatically suffix the extension.
  5. Add the following code into myhomepage.dart file:
    import 'package:flutter/material.dart';
    
    class MyHomePage extends StatelessWidget{
    
      final String title;
      MyHomePage({this.title}) {
      }
    
      @override
      Widget build(BuildContext context) {
        return new Scaffold(
          appBar: new AppBar(
            title: new Text(title,style: new TextStyle(fontSize: 15.0),),
          ),
        );
      }
    } 
    • Here, we have created MyHomePage class which extends StatelessWidget
    • Create constructor and in argument use {this.title}, to provide named parameter and value to final title variable. The key difference between const and final is, const needs to be defined at compile time and final variable could be defined at time of first initialisation
    • We need to override Widget build(BuildContext context) method and return Scaffold object containing information of AppBar
    • Here appBar is property of Scaffold class, which needs to be initialised with AppBar object, where you can specify title to be displayed
  6. First Run, either key Shift+F10 or press play button to run your project, please mind your emulator should be running, to see your application:

    Flutter Getting Started: Tutorial 1 Basics

    Debug ribbon at top-right corner means we are running this app in debug mode. With this, we have completed our Task#1.

  7. Now for Task#2, as everything in Flutter is widget, we will create a new class MySnackBarClass and provide the same as object to body property of Scaffold in MyHomePage, so build method of MyHomePage would look like this:
      Widget build(BuildContext context) {
      return new Scaffold(
        appBar: new AppBar(
          title: new Text(title,style: new TextStyle(fontSize: 15.0),),
        ) ,
        body: new MySnackBarClass()
      );
    }
    

    New addition is marked in bold.

  8. Now create class MySnackBarClass and provide the following code to it:
    class MySnackBarClass extends StatelessWidget{
      @override
      Widget build(BuildContext context) {
        return new Container(
          child: new Center(
              child: new Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <widget>[
                  new RaisedButton(
                    onPressed: (){
                      final mySnackBar = new SnackBar(
                          content: Text('Hello from SnackBar'), //text to display
                          duration: Duration(seconds: 10),    // Duration to display
                      );
                      Scaffold.of(context).showSnackBar(mySnackBar);
                    },
                    child: new Text("Click Me"),
                    color: Colors.amber,
                  ),
                ],
              )
          ),
        );
      }
    }
    </widget>

    Explanation of the code:

    • Here, we are returning Container object, which will act as container for putting various UI elements
    • We want our content to be center aligned to the page, so we used Center widget and provide its child object of Columns and making its main axis alignment to center
    • Since we can place multiple widgets in the column widget, so it has children property instead of child property, which take array of widget
    • Here we provided object of RaisedButton, whose color is amber, label is Click Me and onPressed is anonymous function displaying SnackBar
    • We created Snackbar object with text and its visibility duration
    • Lastly, we used Scaffold.of() method to show SnackBar
  9. Use Hot reload to refresh the emulator, in case it doesn’t work, you can perform hot restart

    Flutter Getting Started: Tutorial 1 Basics

    So Task#2 completed here.

  10. For adding the Bottom Navigation bar, we need to utilize bottomNavigationBar property of Scaffold class, we will use the same approach we took in Task#2, we will create a separate class to handle the Bottom Navigation Bar, after changes the code of build method in MyHomePage will look like this:
     Widget build(BuildContext context) {
      return new Scaffold(
        appBar: new AppBar(
          title: new Text(title,style: new TextStyle(fontSize: 15.0),),
        ) ,
        body: new MySnackBarClass(),
        bottomNavigationBar: new MyBottomNavigationBar(),
      );
    }
    

    Here, we would be creating MyBottomNavigationBar class to provide UI elements for bottom bar.

  11. Create MyBottomNavigationBar class, here is what the code looks like:
    class MyBottomNavigationBar extends StatelessWidget{
      @override
      Widget build(BuildContext context) {
        return new ButtonBar(
          alignment: MainAxisAlignment.center,
          children: <widget>[
            new IconButton(icon:new Icon(Icons.airline_seat_recline_normal), onPressed: (){
              print('hello');
            })
          ],
        );
      }
    }

    Here is the explanation for the above code:

    • We are returning ButtonBar object, which provides capability of putting multiple inside its widget tree
    • Put alignment of ButtonBar to center, to display content center aligned
    • Create IconButton with type of airline_seat_recline_normal icon
  12. So Hot reload for last time to see your changes:

    Flutter Getting Started: Tutorial 1 Basics

So we come to the end of this tutorial, stay tuned for more. You can also look at the source code on GitHub https://github.com/thatsalok/FlutterExample/tree/master/tutorial1

Points of Interest

Please go through these articles. It might give a headway, where the wind is actually flowing:

  1. Flutter — 5 reasons why you may love it
  2. What’s Revolutionary about Flutter
  3. Why Flutter Uses Dart

Flutter Tutorial

  1. Flutter Getting Started: Tutorial 2 – StateFulWidget
  2. Flutter Getting Started: Tutorial 3 Navigation

Dart Tutorial

  1. DART2 Prima Plus – Tutorial 1
  2. DART2 Prima Plus – Tutorial 2 – LIST

History

  • 05-July-2018: First version
  • 11-July-2018: Updated with other tutorial references
  • 14-July-2018: Updated with other tutorial references, general article fixes