Tutorial 3: Flutter Basics

Introduction to Dart

Dart is an object-oriented language that you can use to write simple scripts or full-featured apps. Whether you’re building mobile, web, or desktop applications, Dart’s flexibility and expressiveness make it a joy to use.

Key Features

  • Everything is an Object: Dart is a purely object-oriented language, meaning even basic types like numbers, booleans, and functions are objects. All objects inherit from the Object class.
  • Sound Type System: Dart uses sound typing, which can be both static (checked at compile-time) and dynamic (checked at runtime). Types are optional but encouraged for better readability and error checking.

Syntax

  • Variables: Use var to declare a variable when the type is obvious. Use dynamic when you want a variable to be dynamically typed. Dart also supports strong type definitions.

var name = ‘Flutter’; // Inferred as String
int year = 2021; // Explicitly typed as int
dynamic myVariable = ‘Dynamic’; // Can hold any type

  • Functions: Dart is a true object-oriented language, so even functions are objects and have a type, Function.

void main() {
  print(‘Hello, Flutter!’);
}

int add(int a, int b) {
  return a + b;
}

  • Control Flow Statements: Dart supports standard control flow statements such as if, for, and while.

if (year >= 2021) {
  print(‘Welcome to the future of app development!’);
}

for (var i = 0; i < 5; i++) {
  print(‘index $i’);
}

  • Classes and Inheritance: Dart uses class-based inheritance.

class Vehicle {
  void start() {
    print(‘Starting…’);
  }
}

class Car extends Vehicle {
  @override
  void start() {
    super.start();
    print(‘Car started’);
  }
}

Dart in Flutter

In Flutter, Dart is used for scripting your app’s logic and defining the UI itself. Widgets, the core concept of Flutter’s UI, are written in Dart, making the language the backbone of your Flutter applications.

  • Declarative UI: Flutter uses a declarative style for building UIs. With Dart, you describe what your UI should look like, and the Flutter framework renders it.
  • Hot Reload: Dart’s features enable Flutter’s hot reload functionality, allowing developers to see changes in real-time without restarting the app.

Flutter Architecture and Widgets

Widget-based Architecture

In Flutter, everything you see on the screen is a widget. Widgets are the basic building blocks of a Flutter app’s user interface, encapsulating both the visual representation and the way interactions are managed. This modular approach allows for a highly customizable and reusable UI, enabling developers to create complex layouts from simple elements.

  • Composability: Widgets can be nested within each other to build complex interfaces. For example, a button widget might contain text and icon widgets.
  • Immutability: Widgets are immutable, meaning their properties can’t change — all changes require widgets to be rebuilt with new properties.

Stateless vs. Stateful Widgets

Stateless Widgets

These widgets are immutable, meaning their properties can’t change during runtime. A Stateless Widget renders once and does not change its state or properties over time. Examples include icons, text, and buttons that do not require interaction to change their appearance.

Stateful Widgets

Unlike Stateless Widgets, Stateful Widgets are dynamic. They can change their state during runtime based on user interaction or data changes. This makes them ideal for interactive elements like forms, animations, or any UI element that changes over time.

Stateful Widgets are composed of two classes: a StatefulWidget class that creates an instance of a State class. The State class holds the state for the widget and can trigger a rebuild of the widget by calling setState().

Widget Tree and UI Rendering

Flutter apps are organized in a hierarchical structure known as the Widget Tree. This tree represents the composition of widgets in the app, from the root widget down to the smallest elements. Flutter walks through this tree to render the UI, allowing for efficient updates and rendering of the visual elements.

  • Building the UI: Developers define the UI by composing widgets into a tree, starting with a root widget (e.g., MaterialApp for Material Design applications) and adding children widgets that define the app’s structure and layout.
  • Rendering Process: Flutter’s rendering engine paints the UI by visiting each widget in the tree and deciding how it should be displayed based on its properties and the current state. This process efficiently updates the UI whenever changes occur, ensuring smooth and responsive user experiences.

Creating Your First Flutter App

Scaffold and Basic Widgets

The Scaffold widget provides a framework that implements the basic material design layout of the Flutter app. It offers a variety of pre-designed elements and behaviors, such as app bars, floating action buttons, and snack bars.

  1. Create a New Flutter Project: If you haven’t already, start by creating a new Flutter project. Open your terminal or command prompt, navigate to your desired directory, and run flutter to create my_first_flutter_app.
  2. Open the Main Dart File: Navigate to your project directory and open the main.dart file located in the lib folder. This file is the starting point of your Flutter app.
  3. Use Scaffold: Replace the contents of main.dart with the following code to create a basic app structure using the Scaffold widget.

import ‘package:flutter/material.dart’;

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text(‘My First Flutter App’),
        ),
        body: Center(
          child: Text(‘Hello, Flutter!’),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {},
          child: Icon(Icons.add),
        ),
      ),
    );
  }
}

Running and Testing Your App

The simple UI you’ve just defined includes an app bar with a title, a central text widget saying “Hello, Flutter!” and a floating action button with a plus icon. These components are built using basic widgets that Flutter provides, demonstrating how widgets are the core elements of the UI.

Running and Testing Your App

  1. Choose a Device: Before running your app, ensure you have an emulator running or a physical device connected to your computer. You can check the connected devices by running flutter devices in your terminal or command prompt.
  2. Run Your App: Navigate to the root of your Flutter project in the terminal or command prompt and run the command flutter run. This command compiles your app and launches it on the selected device or emulator.
  3. Hot Reload: As you change your app, use Flutter’s hot reload feature to see the results instantly without fully restarting your app. Save your changes in your code editor, and the app should update automatically on your device.
  4. Testing on Different Devices: To ensure your app looks good and works well on different screen sizes and devices, try running it on various emulators or physical devices. Pay attention to layout issues or any UI elements that might not adapt well to different screen dimensions.

Tutorial 1: Introduction to Flutter

What is Flutter?

Flutter is an open-source UI software development kit created by Google. It allows developers to build natively compiled mobile, web, and desktop applications from a single codebase. Flutter is known for its fast development cycles, expressive and flexible UI, and excellent performance.

History and Development by Google

Flutter was first introduced by Google in 2015 and has rapidly evolved into one of the most popular frameworks for app development. Its initial release was known as Sky, running on the Android operating system. Flutter’s development was driven by the need for an efficient and effective way to create high-performance, cross-platform mobile applications.

Google released Flutter 1.0, its first stable version, in December 2018. Since then, the framework has seen significant updates, including web and desktop application support, proving its versatility beyond mobile app development. The Flutter ecosystem has grown to include a rich set of widgets, tools, and plugins that support its use in various application development scenarios.

Flutter’s unique approach to UI design revolves around widgets, which are the building blocks of a Flutter app. These widgets help you create a user interface that is as expressive and dynamic as possible.

The framework is built on the Dart programming language developed by Google. Dart’s focus on front-end development makes it an ideal match for Flutter, providing a reactive framework that facilitates the creation of visually attractive and highly interactive applications.

Why Flutter?

Flutter offers a unique combination of features that cater to the needs of modern app developers, emphasizing efficiency, aesthetics, and community support. Let’s explore the reasons why Flutter is an excellent choice for beginners and experienced developers alike.

1. Cross-platform Development

One of the most compelling reasons to choose Flutter is its cross-platform development capability. With Flutter, you can write your application code once and deploy it on multiple platforms, including iOS, Android, web, and desktop.

This speeds up the development process, ensures consistency, and reduces the effort required to maintain and update the application for different platforms. Cross-platform development with Flutter means reaching a wider audience with less code, making it an efficient solution for app development.

2. Hot Reload Feature

Flutter’s hot reload feature is a game-changer for developers. It allows you to instantly see the changes made in the code in the app without needing to restart it. This feature significantly speeds up the development process by enabling quick experimentation, building UIs, adding features, and fixing bugs in real-time. Hot reload enhances developer productivity and makes the process of learning Flutter more interactive and enjoyable.

3. Rich Widget Library

Flutter comes with a comprehensive and rich set of pre-designed widgets that cover many needs for app development right out of the box. These widgets are highly customizable and can be easily adapted to create complex and beautiful user interfaces.

With the help of Flutter’s widget library, you can add text inputs, sliders, buttons, or scrolling lists. The ability to customize and extend these widgets allows developers to create unique and expressive UIs that stand out.

4. Community and Support

Flutter has a vibrant and growing community of developers. Since its release, it has garnered significant attention and support from individuals and companies around the world. The Flutter community contributes to the ecosystem by developing packages, tools, and plugins that extend Flutter’s capabilities.

Google’s commitment to Flutter’s development ensures that it remains cutting-edge and that developers can access the latest features and improvements. Whether you’re facing a technical challenge or looking for inspiration, the Flutter community is an invaluable resource.

Benefits of Using Flutter

Let’s explore the key benefits of using Flutter:

1. Cost Efficiency

Developing apps with Flutter can significantly reduce the cost associated with app development. Since Flutter allows for cross-platform development from a single codebase, you save on the resources and time required to develop, test, and manage separate apps for iOS and Android.

This unified approach accelerates the development process and simplifies the maintenance and updating of apps, further cutting down costs. For startups and businesses looking to develop apps on a budget, Flutter’s cost efficiency is a major advantage.

2. Consistent UI and Logic Across Platforms

Flutter ensures a consistent user interface (UI) and business logic across all platforms. Flutter eliminates the worry of UI inconsistencies or separate logic implementations for different platforms.

This is because Flutter uses its own rendering engine to draw widgets, making it independent of the platform. As a result, the app looks and feels the same on iOS, Android, web, or desktop, providing a unified experience to users regardless of the device.

3. Vibrant Community and Support

The Flutter community is an ever-growing ecosystem of passionate developers, contributors, and enthusiasts. This vibrant community offers extensive support through forums, social media, and other online platforms where developers share their knowledge, experiences, and solutions to common problems.

The availability of numerous packages and plugins developed by the community extends Flutter’s capabilities, making adding complex functionalities to your apps easier. The strong community support around Flutter helps solve development challenges and fosters learning and collaboration.

4. Ease of Learning

For beginners, Flutter is an accessible and straightforward framework to pick up. Its comprehensive documentation, tutorials, and learning resources make it easy for new developers to start building apps quickly.

The Dart programming language, used by Flutter, is easy to learn, especially for those with experience in object-oriented languages. The hot reload feature also makes the learning process more interactive, allowing beginners to see the results of their code changes immediately, enhancing their understanding of Flutter’s concepts and capabilities.

Use Cases

Flutter enables developers to build high-quality applications that cater to diverse needs from mobile to web, desktop, and even embedded devices.

Let’s explore some of the key use cases where Flutter shines.

1. Mobile Applications

Flutter was initially designed to provide a modern framework for mobile development. It excels in building visually appealing and performant iOS and Android apps from a single codebase.

Whether you’re creating a sophisticated e-commerce app, a lively social media platform, an engaging game, or a productivity tool, Flutter’s rich set of widgets and tools allows you to implement complex UIs and functionalities easily. Its ability to compile to native code ensures that apps run smoothly, providing a seamless user experience.

2. Web Applications

With the introduction of Flutter for the Web, developers can now use the same codebase to deploy their apps as web applications. This capability significantly simplifies the development process for projects that require both mobile and web presence.

Flutter’s web support is optimized for high performance and visual consistency, ensuring that your web app looks and feels like your mobile app, providing a unified experience across platforms.

3. Desktop Applications

Flutter extends its cross-platform development capabilities to Windows, macOS, and Linux desktop applications. This means you can create desktop apps with the same Flutter code used for mobile and web applications.

The ability to build desktop apps with Flutter opens up opportunities for developing more complex, resource-intensive applications that benefit from desktop computers’ computing power, storage, and screen size.

4. Embedded Devices

Although still an emerging area for Flutter, its potential for use in embedded device applications is significant. Flutter’s efficient performance and customizable UI capabilities make it suitable for embedded systems with graphical interfaces, such as smart home devices, in-car infotainment systems, and wearables.

As Flutter continues to evolve, its application in the embedded devices domain is expected to grow, offering developers a unified framework for building apps across various platforms and devices.

Real-World Examples of Flutter Apps

1. Google Ads

The Google Ads app is one of the most prominent examples of Flutter in action. It is designed to help users manage their ad campaigns on the go, the app leverages Flutter’s capabilities to deliver a smooth and intuitive user experience across both iOS and Android platforms. With features like campaign statistics, real-time alerts, and suggestions for improving ad performance, the Google Ads app demonstrates Flutter’s ability to handle complex data visualization and user interactions efficiently.

2. Alibaba

One of the world’s largest e-commerce platforms, Alibaba utilized Flutter to create its Xianyu app, catering to millions of users. By choosing Flutter, Alibaba managed to enhance its app development process, achieving a consistent look and feel across different platforms while maintaining high performance.

The success of Xianyu showcases Flutter’s scalability and its suitability for building large-scale e-commerce applications that require robust features and an engaging user interface.

3. Reflectly

Reflectly is a personal journal and mindfulness app that uses artificial intelligence to help users navigate their thoughts and feelings. Built with Flutter, Reflectly offers a beautifully designed, highly interactive experience that leverages advanced UI elements and animations to engage users. The app’s smooth performance and visually appealing design highlight Flutter’s capabilities in creating apps that are not only functional but also aesthetically pleasing.