Sub topic 2
Creating and running your first project
This chapter assumes the Flutter SDK is installed, flutter doctor reports no blocking problems, and you can run commands in a terminal. Dart, the language Flutter uses, should be familiar enough to read classes and constructors.
Creating and running a project
A Flutter project is a folder containing Dart code, assets, and platform host folders. Generate one with:
flutter create my_first_app
cd my_first_app
flutter runflutter create writes the starter files. flutter run builds the app and launches it on the selected device. Use flutter devices to list targets, then pass one with -d, such as flutter run -d chrome.
Tour of the generated project
| Path | Purpose |
|---|---|
| `lib/main.dart` | App entry point and the Dart code you edit most |
| `pubspec.yaml` | Project name, version, dependencies, and assets |
| `pubspec.lock` | Exact dependency versions resolved by pub |
| `test/` | Automated test files |
| `android/`, `ios/`, `web/`, `macos/`, `windows/`, `linux/` | Platform host projects you rarely edit |
Widgets and the widget tree
A widget is a Dart class that describes part of the interface. Widgets nest inside one another, forming a widget tree. runApp attaches the root widget to the screen.
Building UI with StatelessWidget
A StatelessWidget holds no mutable state. Its build method returns the widget tree from its constructor inputs. Flutter calls build when the widget first appears and whenever its parent rebuilds it.
import 'package:flutter/material.dart';
void main() {
runApp(const GreetingApp());
}
class GreetingApp extends StatelessWidget {
const GreetingApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: Scaffold(
body: Center(
child: Text('Hello, Flutter'),
),
),
);
}
}Exercise
Which method must a StatelessWidget override, and what type does it return?
Show answer
It overrides build(BuildContext context), which returns a Widget that describes the UI.