Flutter Documentation
Build Android, iOS and web apps from one Dart codebase — widgets, layouts, navigation, state, APIs and release.
Flutter is Google's toolkit for building Android, iOS, web and desktop apps from one Dart codebase. Everything on screen is a widget, and the UI is rebuilt from your data. New to the language? Start with the Dart docs.
1. Introduction
| Why Flutter | What it means |
|---|---|
| One codebase | The same code runs on Android, iOS, web and desktop |
| Hot reload | Save a file and see the change in about a second |
| Own rendering | Flutter draws every pixel itself, so apps look the same everywhere |
| Rich widgets | Material (Android style) and Cupertino (iOS style) come built in |
2. Setup and First App
flutter doctor # checks your setup and tells you what is missing
flutter create my_app # new project
cd my_app
flutter run # run on a connected phone or emulator
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Hello',
home: Scaffold(
appBar: AppBar(title: const Text('Codify')),
body: const Center(child: Text('Hello, Flutter!')),
),
);
}
}
Your code lives in lib/, and packages and assets are listed in pubspec.yaml.
3. Stateless and Stateful Widgets
A StatelessWidget only depends on what it is given. A StatefulWidget keeps data that changes; calling setState rebuilds it.
class Counter extends StatefulWidget {
const Counter({super.key});
@override
State<Counter> createState() => _CounterState();
}
class _CounterState extends State<Counter> {
int count = 0;
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Count: $count'),
ElevatedButton(
onPressed: () => setState(() => count++),
child: const Text('Add'),
),
],
);
}
}
Lifecycle of a State: initState (once, at the start) → build (many times) → dispose (once, clean up controllers here).
Common mistake: changing a variable without
setStateupdates the data but not the screen.
4. Layout Widgets
| Widget | Use |
|---|---|
Row / Column |
Children side by side / one below another |
Stack |
Children on top of each other |
Container |
Padding, margin, colour, border, size |
Padding, SizedBox, Center |
Spacing and alignment |
Expanded / Flexible |
Share the free space in a Row or Column |
ListView.builder |
Long scrolling lists, built only as needed |
GridView.builder |
Scrolling grids |
ListView.builder(
itemCount: students.length,
itemBuilder: (context, i) => ListTile(
leading: const Icon(Icons.person),
title: Text(students[i].name),
subtitle: Text('${students[i].marks} marks'),
),
)
Common mistake: a yellow-and-black overflow stripe means a child is bigger than its parent — wrap it in
Expandedor make the area scrollable.
5. Forms and Input
final formKey = GlobalKey<FormState>();
final email = TextEditingController();
Form(
key: formKey,
child: Column(children: [
TextFormField(
controller: email,
decoration: const InputDecoration(labelText: 'Email'),
validator: (v) => v != null && v.contains('@') ? null : 'Enter a valid email',
),
ElevatedButton(
onPressed: () {
if (formKey.currentState!.validate()) print(email.text);
},
child: const Text('Save'),
),
]),
)
Call email.dispose() in dispose() so the controller doesn't leak memory.
7. State Management
setState is fine inside one widget. To share data across screens, use a state library. Provider is the simplest:
class Cart extends ChangeNotifier {
final items = <String>[];
void add(String item) {
items.add(item);
notifyListeners(); // rebuilds every widget that is watching
}
}
// at the top of the app
ChangeNotifierProvider(create: (_) => Cart(), child: const MyApp());
// in any widget below it
final cart = context.watch<Cart>(); // rebuilds when it changes
context.read<Cart>().add('Book'); // use in callbacks, no rebuild
| Option | Good for |
|---|---|
setState |
State of a single widget |
| Provider | Small and medium apps |
| Riverpod | Provider's safer successor; testable, no context needed |
| Bloc | Large apps and teams that want strict structure |
8. Calling an API
import 'dart:convert';
import 'package:http/http.dart' as http;
class Post {
final int id;
final String title;
Post({required this.id, required this.title});
factory Post.fromJson(Map<String, dynamic> j) => Post(id: j['id'], title: j['title']);
}
Future<List<Post>> fetchPosts() async {
final res = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
if (res.statusCode != 200) throw Exception('Failed: ${res.statusCode}');
final list = jsonDecode(res.body) as List;
return list.map((e) => Post.fromJson(e)).toList();
}
Show it with FutureBuilder, which handles loading and errors:
FutureBuilder<List<Post>>(
future: postsFuture, // create it in initState, not in build
builder: (context, snap) {
if (snap.connectionState == ConnectionState.waiting) return const CircularProgressIndicator();
if (snap.hasError) return Text('Error: ${snap.error}');
final posts = snap.data!;
return ListView(children: [for (final p in posts) ListTile(title: Text(p.title))]);
},
)
Common mistake: creating the Future inside
buildsends a new request on every rebuild.
9. Saving Data
| Need | Package |
|---|---|
| Small settings (theme, token) | shared_preferences |
| Local database | sqflite, drift, hive |
| Secrets | flutter_secure_storage |
| Cloud data and login | Firebase |
final prefs = await SharedPreferences.getInstance();
await prefs.setBool('dark', true);
final dark = prefs.getBool('dark') ?? false;
10. Themes, Assets and Packages
# pubspec.yaml
dependencies:
http: ^1.2.0
provider: ^6.1.0
flutter:
assets:
- assets/images/
MaterialApp(
theme: ThemeData(colorSchemeSeed: Colors.indigo, useMaterial3: true),
darkTheme: ThemeData.dark(useMaterial3: true),
themeMode: ThemeMode.system,
)
Image.asset('assets/images/logo.png');
Find packages on pub.dev and add them with flutter pub add http.
11. Testing and Release
testWidgets('counter adds one', (tester) async {
await tester.pumpWidget(const MaterialApp(home: Scaffold(body: Counter())));
await tester.tap(find.text('Add'));
await tester.pump();
expect(find.text('Count: 1'), findsOneWidget);
});
flutter test # run tests
flutter build apk --release # Android APK
flutter build appbundle # for the Play Store
flutter build web # website
12. Practice Problems
- A counter app with + , − and reset buttons.
- A to-do list with add, tick and delete, saved with
shared_preferences. - A weather app that calls an API and shows loading and error states.
- A quiz app with a score screen, passing data between pages.
- A notes app with login and cloud sync using Firebase.
13. Interview Questions
Stateless vs Stateful widget? Stateless depends only on its inputs; Stateful holds data that changes and rebuilds with setState.
What are the widget, element and render trees? Widgets are light descriptions, elements keep their place in the tree and hold state, render objects do layout and painting.
Why use const constructors? Flutter reuses const widgets instead of rebuilding them, which saves work.
What is BuildContext? A widget's location in the tree, used to find things above it like the theme or a provider.
Hot reload vs hot restart? Reload injects new code and keeps state; restart runs the app again and loses state.
What are keys for? They help Flutter match widgets to their state when lists reorder.
Future vs Stream? A Future gives one value later; a Stream gives many values over time (StreamBuilder shows them).
context.watch vs context.read? watch rebuilds on change; read gets the value once, for use in callbacks.
14. Cheat Sheet & References
Commands
flutter doctor
flutter create app_name
flutter run
flutter pub add http
flutter test
flutter build apk --release
Core widgets
Scaffold(appBar: AppBar(), body: child)
Row(children: []) / Column(children: [])
Container(padding: EdgeInsets.all(8), child: child)
Expanded(child: child)
ListView.builder(itemCount: n, itemBuilder: (c, i) => child)
Text('Hi') / Image.asset('a.png') / Icon(Icons.home)
ElevatedButton(onPressed: () {}, child: Text('OK'))
State and navigation
setState(() => count++);
Navigator.push(context, MaterialPageRoute(builder: (_) => Page()));
Navigator.pop(context);
context.watch<Cart>(); context.read<Cart>();