DEV Community

Cover image for A Developer's Guide to Flutter
Karan Shah for SoluteLabs

Posted on • Originally published at blog.solutelabs.com

A Developer's Guide to Flutter

Since it's much-awaited launch, Flutter has caught a lot of attention, and we're excited about it too! I'm hoping that a massive chunk of non-game apps will transition to flutter, and in anticipation, we are therefore training our team on it as well.

Since there are new, but few, resources scattered over the internet to learn flutter - we've compiled our Flutter tutorial to get developers off their feet and start developing apps for Flutter.

In this Flutter guide for beginners, we will cover:

  • Flutter: What, How, and Why?
  • Setting up Flutter
  • Dart Basics
  • Flutter Basics
  • Widgets
  • Layouts
  • Interactive Widgets
  • Designing an app: Forms, Gestures, and Images
  • Lists & Navigation
  • Networking
  • JSON and Serialization
  • Dependency Management
  • State Management
  • Testing (Unit and Integration)

Flutter: What, How, and Why?

What is Flutter, and how is it different? Just remember this - Flutter was built to work for any device with a screen and works with:

  • iOS and Android
  • Web and Desktop (Mac, Windows, and Ubuntu) - Even support PWA
  • Auto
  • Raspberry Pi (POC stage)

Check out this video from Google; it's a great place to get a grasp - comparing Native Development, Hybrid App Development, React Native Development, and finally, Flutter App Development.

Here is the latest news on the launch of the new version of Flutter and Dart programming language-

Setting up Flutter

Flutter is relatively straightforward to set up and depending on what OS you're using; you can check out the steps in this official Flutter tutorial:

https://flutter.dev/docs/get-started/install

But in case, you do run into something, check out here: https://github.com/flutter/flutter/wiki/Workarounds-for-common-issues#flutter-installation

The reason we ask that you setup Flutter before Dart is because when you install Flutter, you install Dart too, and while you can separately install dart, it would an unnecessary step. Flutter will decide which dart version will be used, so installing different dart version will be ambiguous as well.

Once you've downloaded and unzipped Flutter, you should see something like this on running the flutter command at the console:

flutter development

If you're new to mobile development in general, you will need to download Xcode and Android Studio (and toolchain), as well. Once you've setup Flutter, scaffolding a new project is just one command.

Dart Basics

Flutter uses Dart language to build Apps. To understand why Flutter uses dart, check out my previous blog and down to the section - How Flutter was born

Flutter and Chrome use the same rendering engine - SKIA. Instead of interacting with native APIs, it controls every pixel on the screen, which gives it the much necessary freedom from the legacy baggage as well as the performance it has.

Do give the official doc a read, but I found this one to be good at explaining dart

Why Flutter Uses Dart

P.S. You can follow up with dart updates on their medium account

Now, you know why Google choose Dart - so let's get your hands dirty!

Learn Dart

Check out the official docs of Dart language, a tour, and their language samples.

Once you have an overview, head over to http://jpryan.me/dartbyexample/ and do all the examples religiously.

Practice, Practice, Practice!

Edit your code on DartPad for starters and get a better grip. I'm sure you'll be up and running in no time!

My First Hello, World! in Dart

After, you're done with dartbyexample, head over to exercism, and complete their dart track. It's trendy, so in case it's full, you can do the practice track too.

Dart | Exercism

Flutter Basics

Now that you're familiar with Dart, it's finally time to move on to Flutter

penguin gif

Let's start with the technical overview here:

Technical overview

And scaffold a new flutter app with:

$ flutter create app_name

And you should see something like this:

android studio

Open the project on the Android Studio, download the emulator, and an Android version if not done already and run the project - and et voila!

Flutter demo

Understand as to how should you structure your project directory and understand which files are meant for which purpose

Flutter Project Structure

Now that you've setup flutter, it's time to do what all developers do! Use other's code 😆 - what I meant is to set up the package file: pubspec, written in YAML

The pubspec file

Widgets

Remember - Everything's a widget in Flutter

If you've not read the technical overview as we asked you before, go back and read it :) You will get a fair idea of what widgets are. Widgets come in two flavors: stateless and stateful

Stateless Widgets are those whose state doesn't change like a button or an image. As the name states, it doesn't change its state when an action is performed on the screen.

Check out the short video series, and it's documentation by Google to explore in-depth (I'm attaching the first video in the series).

When a widget needs to hold some state like a current page in PageView, the currently selected tab in a BottomNavigationBar, Stateful widgets are the right choice to make.

StatefulWidgets can hold the current state of a Widget. Instead of a widget build method, a Stateful widget has a State build method which calls each time we explicitly call setState.

And Similarly, check out the documentation (it has the video inside) for the stateful widgets here:

StatefulWidget class

Flutter 1.9 was released at GDD China with a host of new features and a mark that the community is multiplying (and that you can't ignore China now)

Layouts in Flutter

As we discussed earlier, everything is a widget in Flutter - including layout models.

Check out the documentation here:

Layouts in Flutter

Widgets such as the rows, columns, and grid are layout widgets (which we don't see on screen) that helps other visible widgets to arrange, constraints, and align.

⏰ Time for Codelab: Write your First Flutter App : Part-1

And, Some more Widgets!

Flutter comes with a suite of powerful basic Widgets such as Text, Column, Row, Stack, and Container. The basic widgets will help you creating custom views as you want.

If your app follows material design guidelines, Flutter has a lot to cover by default. Flutter provides several widgets that support Material Design. It includes widgets such as MaterialApp, AppBar, Scaffold, etc.

Material Navigation Drawer (https://material.io/components/navigation-drawer/#)

Flutter also includes the iOS-centric Cupertino component package. It covers widgets such as CupertinoApp, CupertinoNavigationBar, etc.

Cupertino NavigationBar (https://developer.apple.com/design/human-interface-guidelines/ios/bars/navigation-bars/)

Interactive Widgets

So far, we have seen Widgets that display information on-screen or arrange other widgets. For the real app, it is equally essential to make the app interactive and get user's input in various forms like Gesture, taps, etc.

To achieve this, Flutter has numbers of StatefullWidgets such as Checkbox, Radio, Slider, InkWell, Form, and TextField, etc. These widgets are capable enough to maintain their state (e.g., Text we are entering in TextField, whether a CheckList is checked or not.)

Go and check out the below example to add Favorites/Non-Favorites functionality to your app.

Adding interactivity to your Flutter app

Time for Codelab: Write your First Flutter App : Part-2

As you have reached here, you should be clear with What is Widgets? and Types of Widget

Now you must be curious about what are all widgets available in Flutter?

So here is a Widget Catalog, Check all the Widgets that make Flutter development relaxed and Fun 😍

Widget catalog

Flutter Cookbook

And here we go, It's time to learn Flutter for real apps. I mean Apps that have Multiple screens, Images, Network dependency, and all.

So, Let's begin.

Designing an App

Check the below app illustration.

-----------------

This Simple looking app has these features 👇

  1. Navigation Drawer
    https://flutter.dev/docs/cookbook/design/drawer

  2. SnackBar
    https://flutter.dev/docs/cookbook/design/snackbars

  3. Custom Fonts (A Text have its own Style 😉)
    https://flutter.dev/docs/cookbook/design/package-fonts

  4. A Text-based on Orientation (Bigger fonts in Landscape)
    https://flutter.dev/docs/cookbook/design/orientation

  5. And, Multiple Tabs
    https://flutter.dev/docs/cookbook/design/tabs

Note here: OrientationBuilder is independent of the device's orientation. Instead, It calculates the current Orientation by comparing the width and height available to the parent widget. To determine the device's orientation you can refer MediaQuery.of(context).orientation

Forms

Flutter has a Form widget that helps to build a form that efficiently manages the essential requirement of a Form, e.g., State of a Form, Validation, etc. Check out the complete guild in the below documentation.

Cookbook

Gestures

To get the user inputs and some-time to make the app super interactive, we maximize the use of Gestures. Flutter has pre-built widgets to cover this.

  1. Adding Material Ripple Effect
    https://flutter.dev/docs/cookbook/gestures/ripples

  2. Handle Taps
    https://flutter.dev/docs/cookbook/gestures/handling-taps

  3. Swipe to Dismiss
    https://flutter.dev/docs/cookbook/gestures/dismissible

Images

To make apps beautiful and engaging, we use Images. Flutter provides an Image widget to display an image in the Flutter app from various sources.

  1. Display Images from Network

Display images from the internet

  1. Display Image with Placeholder & with Fade-in Animation

Fade in images with a placeholder

  1. Sometimes it's handy to Load image from network and cache it in local storage to make it quickly available next time.

Work with cached images

Showing more data using List

To accommodate more data, we use List to show them. The list can be horizontally or linearly.

Flutter has a GridView and ListView. These are basic widgets with different contractors to identify how they can be used.

  1. Create a grid list

Create a grid list

  1. Create list horizontally

Create a horizontal list

  1. The list can have different types of Item. E.g., a header & items to it. Check here how you can cover such cases in ListView.

Create lists with different types of items

  1. Floating app bar and Nested scrolling using SliverList

Place a floating app bar above a list .

Don't forget to check out this awesome article by Emily Fortuna to understand Slivers in depth

  1. Sometimes we have predefined arbitrary items to be placed in a List. e.g., Setting categories. In ListView, you can pass custom items (in the form of Widgets) to its children.

Use lists

  1. Sometimes a List has more items then the viewport of a screen. In such cases, it makes no sense to build all the items at once. Flutter has ListView.Builder that uses the Lazy rendering approach to create list items efficiently.

Work with long lists

If you have more items in a list and looking to paginate them. Here is a good article I found 👇

Navigating between screens aka routes

Most apps contain multiple screens to display data in a well-organized manner. 

In Flutter, we can do navigation-related operations using Navigator
Check below diagram to understand how Flutter manages multiple routes, and later, we will discuss how to navigate up and forth between them.

-----------------

  1. Navigate to a new screen and back

Navigate to a new screen and back

  1. Pass data to new screens and retrieve results.

Send data to a new screen

Return data from a screen

So far, what we have seen is suitable for small projects. But when the project grows, we want to manage all routes at a single place. Also, we might need to address below questions

  1. How many routes we have?
  2. How to initialize each route?
  3. What data is required by each route? etc..
  1. To manage all this efficiently, Flutter has named routes.

Navigate with named routes

  1. Pass arguments in named routes.

Pass arguments to a named route

And, What about this animation while navigating to a new screen?

Hero animation (https://flutter.dev/docs/cookbook/navigation/hero-animations)

  1. Animate a widget across screens

Animate a widget across screens

Networking

Most apps we come across nowadays, are generally connected with third party server and makes requests to the server to fetch or post data.

In Flutter, we can use Http as a third party pub to do such stuff.

http | Dart Package

  1. Fetch data from the network

Fetch data from the internet

  1. Make authenticated requests

Make authenticated requests

  1. Work with web sockets

Work with WebSockets

Flutter has few more pubs available, which do such stuff more efficiently. Don't forget to take a look at the below pubs.

dio | Dart Package

chopper | Dart Package

Using JSON and Serialization

In Flutter, we generally have two strategies for JSON serialization. Manual parsing and automated serialization using code generation.

Runtime reflection is disabled in Flutter, resulting we cannot have libraries like GSON, Jackson or Moshi

Check out the full guide with both strategies here:

JSON and serialization

For manual parsing, don't forget to check out this online tool to auto-generate boilerplate for the model class.

Instantly parse JSON in any language | quicktype

Data Persistence

Sometimes we need to persist data in local memory to quickly available whenever we need them.

  1. If you have a relatively small amount of data to be stored in a key-value pair. Consider using shared-preferences. Below is the detailed guide to achieving the same using Flutter.

Store key-value data on disk

  1. You can also read and write files on disk.

Read and write files

  1. If an app needs to persist a large amount of data and also it requires to query them. It is advised to use an SQLite database

Flutter app can use the SQLite database via sqflite pub.

Persist data with SQLite

For easy to use, reactive persistence, check out below pub. Moor is a wrapper around sqflite.

moor_flutter | Flutter Package

Dependency Management

We use so many pubs in the app. It's a great way to work collectively and share code across apps without having to develop everything from scratch.

You can find all the useful packages from here.

Dart packages

With multiple pubs, you might faces issues like conflicts in the version resolving. You can find all the best practices here to be followed while using pubs.

Using packages

And, with all this, you now have completed Flutter cookbook. 👏

An Art of State Management

Introduction

In a typical app, it is a common use-case that a change made at Point-A reflects some changes at Point-B. That is called State management. It can also be understood by the below illustration.

Alt text of image

Flutter has multiple approaches that can efficiently manage the State of the app. Based on project size we can decide the appropriate techniques.

Here we will discuss a few of the possible techniques for State management.

  1. setState way

Adding interactivity to your Flutter app

  1. Inherited Widget

Check out the below video to understand, What is Inherited Widgets?

Also, Check out the complete list of articles here.

List of state management approaches

Remember "Theme.of(context);" and "Navigator.of(context);" you used earlier? That is using the same Inherited Widget concept to access data down in the widget tree.

  1. The Provider Package

The provider is a mixture of DI (dependency injection) and State management built with widgets for widgets.

Official documentation of provider is too good to understand it in depth.

provider - Dart API docs

  1. BLoC Pattern

BLoC is a Simple, Lightweight, and highly testable a predictable state management library for Dart.

Here is an official guide to: Bloc

I also found this good video series explaining BLoC pattern (with Accompanying article series)

There are also other popular State management techniques in the industry. Like Redux and Mobx.

Testing

When the app grows, it becomes hard to test every feature, and then it comes regression too. In such cases, automation testing is the way to go. It helps ensure that the app performs as expected before we release it. 
And so we don't fall in such situations. 😆

Automation testing falls under three categories

  • A unit test tests a single function, method, or class.

  • A *widget test (in other UI frameworks referred to as component test) tests a single widget.

  • An *integration test tests a complete app or a large part of an app.

Check out the introduction to testing in Flutter here

Testing Flutter apps

Unit Testing

The goal of Unit testing is to test a particular Unit of code with Stub/mock dependencies. Verify the code works as expected in different scenarios. A unit test is very fast and doesn't require an actual device to execute.

An introduction to unit testing

While doing Unit tests, any dependent classes should be injectable, so that we can inject a mock or fake implementation of dependancy and verify if everything working as expected. Flutter has a mockito framework that helps to create a mock or fake implementation.

mockito | Dart Package

Widget Testing

Widget Testing (in Flutter) is a UI testing technique. 
The goal of widget testing is to test if particular Widget UI looks as expected, and it's interactive. Widget testing doesn't require a physical device.

We could also test the properties of Widget, like Color, Size, Font Family, etc..
We can also perform user events like tap, gestures, entering text, etc.

An introduction to widget testing

Integration Testing

Integration test work in a pair. The goal here is to test how multiple units work together. Integration testing happens on a real device or emulators.

We can fire a series of User interaction events and expect UI rendering or unit codes to be executed properly.

An introduction to integration testing

BDD: Behavior-driven development

TDD or Unit Tests helps when a stakeholder has strong technical skills. BDD is all about writing a test case from the end user's perspective. This is written in a natural English language.

Testcase can be written in the below format:
Given: the initial context at the beginning of the scenario, in one or more clauses;
when: the event that triggers the scenario;
then: the expected outcome, in one or more clauses.

Internally, a behavior test cases can be a Unit test, widget test, or a combination of both.

BDD helps to understand software functionality from an end-user perspective and becomes a sort of functional documentation.

Flutter has a gherkin that helps us writing Behaviour Test cases.

gherkin | Dart Package


This guide covers all the basics that you would need to know to start with flutter and develop your apps! We hope this helps you on your journey to flutter.

Top comments (18)

Collapse
 
kris profile image
0xAirdropfarmer

Simply the best guide from the developer's perspective. This article has covered just about anything related to flutter. Great to amplify the basic knowledge of flutter. Thanks for this resourceful article. We can also learn a great deal from lots of amazing flutter templates in the market. They help to implement and deploy new apps for startups and businesses quickly preventing development time and cost. A great resource to learn the UI layouts and custom functionalities as well.

Collapse
 
atkaranshah profile image
Karan Shah

Thank you :)

Collapse
 
kamal_bunkar profile image
kamal bunkar

"thanks karan for amazing article. it covered all the basics that a beginners should know. You can add some more values by including some topic like how to release flutter app on apple store and Flutter stateless vs statefull widget .
by the way thanks you. I like your article and have shared it on facebook."

Collapse
 
pablonax profile image
Pablo Discobar

Helpful article! Thanks! If you are interested in this, you can also look at my article about Flutter templates. I made it easier for you and compared the free and paid Flutter templates. I'm sure you'll find something useful there, too. - dev.to/pablonax/free-vs-paid-flutt...

Collapse
 
zalek profile image
zalek

I just started to learn Flutter and here is my problem:

I want to create an object that contains pairs of two strings, lets say a name and city. I also want to access each pair by an index. In Java it would be:
List aList = new List();
Map is not good, because as I know I cannot retrieve specific element lets say for index=n

Any suggestions?

Thanks,
zb

Collapse
 
lexiebkm profile image
Alexander B.K.

If I can understand what you mean, then you can use list of map like so :

  var maplist = [
    {"name": "James Gosling of Java", "city": "Toronto"},
    {"name": "Anders Hejlsberg of C#", "city": "New York"},
    {"name": "Guido von Rossum of Python", "city": "Amsterdam"},
    {"name": "Bjarne Stroustrup of C++", "city": "Kopenhagen"},
    {"name": "Niklas Wirth of Pascal", "city": "Vienna"},
    {"name": "Rasmus Lerdorf of PHP", "city": "Chicago"},
    {"name": "Brendan Eich of JS", "city": "Los Angeles"}
  ];

  for (var n = 0; n < maplist.length; n++) {
    print("${maplist[n]['name']} lives in ${maplist[n]['city']}");
  }
Enter fullscreen mode Exit fullscreen mode

The output is like so :
James Gosling of Java lives in Toronto
Anders Hejlsberg of C# lives in New York
Guido von Rossum of Python lives in Amsterdam
Bjarne Stroustrup of C++ lives in Kopenhagen
Niklas Wirth of Pascal lives in Vienna
Rasmus Lerdorf of PHP lives in Chicago
Brendan Eich of JS lives in Los Angeles

Collapse
 
codemouse92 profile image
Jason C. McDonald • Edited

Everyone seems to have forgotten what Flutter — yes, this Flutter — was originally.

Gesture recognition! (Circa 2012/2013)

Then it was acquired by Google and turned into a development platform. Does it even have gesture recognition anymore?

Collapse
 
kamal_bunkar profile image
kamal bunkar

Thank You for details Explanation. Amazing article. Please add some more value like flutter plugins for text animation and text autosixer.

Collapse
 
leandrit_ferizi profile image
Leandrit Ferizi

Thanks for putting it together :)

Collapse
 
atkaranshah profile image
Karan Shah

Welcome!

Collapse
 
saurabhaswal009 profile image
saurabh singh aswal

Hello everyone I am new in here and so excited to be the part of this dev world. i am atrected here because the good coding stuff, friendly community, healping each others in coding, learn somthings new.
I am a Flutter Developer and created a lots of apps and placed in playstore now i am work in my Personal Project so all the community member please help me if i am stuck in some conditions and i am also available for your help also.

please check out my website and if you give some feedback so i am so happy -->>Dosomthings.com.

Thank's and please connected ❤️❤️❤️

Collapse
 
angelinajasper profile image
Angelina Jasper

Fantastic article, Karan! The insights into Flutter development are incredibly valuable for both beginners and seasoned developers.

I've recently penned a beginner's guide to building Flutter apps myself. Would love to hear your thoughts and any feedback you might have! Keep up the great work!

Collapse
 
asimjibran profile image
Asim Jibran

Awsome writeup and Guide for someone like me who is just into this app development game. I have got an app developed for my Food Delivery business through Kaspar Consulting Services and I think they have done an execllent job with it and should be tried for any flutter related development