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.
- 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.
- 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.
- 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
- 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.
- 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.
- 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.
- 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.