Flutter & Mobile Development
Build Pack List, a one-screen app for packing a bag. Type an item, check it off, delete it, and see your progress. Close the app and reopen it to recover the checklist. The app works in airplane mode because it stores its data on the device.
Dart is the language you write. Flutter supplies widgets, rendering, and tooling. Android and iOS provide the process, keyboard, window, and storage. A Flutter plugin connects Dart code to a platform service when you need one.
flowchart LR
Dart["Dart code: checklist and behavior"] -->|"describes"| Widgets["Flutter widget tree"]
Widgets -->|"renders into"| Window["Android or iOS window"]
Dart -->|"reads and writes through"| Plugin["Shared preferences plugin"]
Plugin -->|"calls"| Storage["Device preferences"]Set up your first device
Windows and Android
- Install the stable Flutter SDK and add its bin directory to PATH. Open a new terminal so it picks up the change. The SDK includes Dart. An editor extension adds tooling such as autocomplete and breakpoints.
- Install Android Studio. In SDK Manager, follow the Flutter Android setup checklist for SDK Platforms and SDK Tools, including Command-line Tools, Platform-Tools, Build-Tools, and the emulator.
- In Device Manager, create a virtual phone and boot it. For a physical phone, enable developer options and USB debugging, connect it by USB, and accept the debugging prompt.
- Run the commands below. Review the Android SDK licenses when prompted. Check that the Android toolchain passes and that your phone or emulator appears in the device list. If several devices appear, use
flutter run -d DEVICE_IDwith the ID shown by Flutter.
flutter --version
flutter doctor --android-licenses
flutter doctor -v
flutter devices
flutter create --platforms=android,ios pack_list
cd pack_list
flutter runThe generated counter app should open on the device. Tap its button and watch the count increase. Change a visible string and press r in the running terminal to hot reload. The existing count normally stays. Press R to hot restart and rerun main(). Stop and start the app again after changing native plugin dependencies.
macOS and iOS
Install Flutter and Xcode on a Mac, initialize Xcode's command-line tools, and install an iOS simulator runtime. Follow the official iOS setup guide for plugin tooling and signing. Start the simulator from Xcode, run flutter devices, and select the simulator with flutter run -d DEVICE_ID. A physical iPhone also requires device trust, Developer Mode, and a signing team.
Flutter SDK installation · Android setup · iOS setup
Dart for this tutorial
Save this snippet as basics.dart outside the app and run dart run basics.dart. It prints Passport, Charger, and Unnamed item on separate lines.
Future<String> formatItem(String? input) async {
final name = (input ?? '').trim();
return name.isEmpty ? 'Unnamed item' : name;
}
Future<void> main() async {
final names = <String>['Passport', 'Charger'];
for (final name in names) {
print(await formatItem(name));
}
print(await formatItem(null));
}String?accepts a string or null. The??operator supplies a fallback when the left side is null.trim()removes whitespace at the ends of a string.finalassigns a variable once. A final list can still have mutable contents. In the app,[...items]copies the list before a change so the visible list stays intact until the save succeeds.Future<String>represents a string delivered later.awaitpauses the current async function until the result is ready. Flutter can keep drawing and responding to events while a storage request is pending.- A class groups data and behavior.
PackingItemhas a name and a packed flag.packed: truesets a named constructor argument. The default is false.
Build a screen with widgets
Stop the starter app and add the Material UI package from the project folder. Start the app again after replacing the source in the first checkpoint.
flutter pub add material_ui:1.11.0Replace the generated lib/main.dart with this first checkpoint and hot restart. Expect the words Pack List in the center of the screen. runApp installs a root widget. MaterialApp provides Material defaults, Scaffold gives a screen its structure, and SafeArea accounts for system insets such as the bottom gesture area.
import 'package:material_ui/material_ui.dart';
void main() => runApp(const MaterialApp(
home: Scaffold(
body: SafeArea(
child: Center(child: Text('Pack List')),
),
),
));A widget describes part of the UI. A widget can contain children, so the descriptions form a tree. In layout, parents pass constraints down, children choose a size within those constraints, and parents position their children. In the final app, a scrollable list gives the form and item rows room when the keyboard reduces the usable height. Inside an item row, Expanded gives the checkbox tile the width left over after the delete button.
flowchart TD
App["MaterialApp"] --> Page["PackingPage"]
Page --> Scaffold["Scaffold"]
Scaffold --> Bar["AppBar"]
Scaffold --> Safe["SafeArea"]
Safe --> List["ListView"]
List --> Form["Form: progress, text field, Add item"]
List --> Row["Row for each visible item"]
Row --> Check["Expanded checkbox tile"]
Row --> Delete["Delete button"]Make the screen interactive
Replace lib/main.dart again and hot restart. Tap Passport to change the check mark. A StatefulWidget describes the screen and a separate State object holds mutable values. Calling setState updates the value synchronously and schedules a rebuild. Flutter calls build again and the checkbox receives the new value.
import 'package:material_ui/material_ui.dart';
void main() => runApp(const MaterialApp(home: PackingDemo()));
class PackingDemo extends StatefulWidget {
const PackingDemo({super.key});
@override
State<PackingDemo> createState() => _PackingDemoState();
}
class _PackingDemoState extends State<PackingDemo> {
bool _packed = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Pack List')),
body: SafeArea(
child: CheckboxListTile(
title: const Text('Passport'),
value: _packed,
onChanged: (value) => setState(() => _packed = value ?? false),
),
),
);
}
}Keep storage calls out of build, which may run repeatedly. In the final app, initState starts the first load, dispose releases the text controller, and mounted checks whether the screen still exists after an await. The packed count is calculated from the list each time the screen builds.
sequenceDiagram
actor User
participant Widget as Checkbox tile
participant State as Packing page state
participant Store as Device store
User->>Widget: Tap Passport
Widget->>State: onChanged
State->>State: Prepare a changed copy
State->>Store: Await save
alt Save succeeds
Store-->>State: Completed
State->>State: Commit copy with setState
State-->>Widget: Rebuild with new checked value
else Save fails
Store-->>State: Error
State-->>User: Show a message and allow another attempt
endSave the checklist on the device
Hot restart the checkbox demo and observe that it resets. The mobile OS can also terminate a backgrounded app, so a field in a State object only lasts while that object exists. Pack List encodes its small checklist as JSON and saves it under one key. On launch it decodes the stored string back into Dart objects.
[{"name":"Passport","packed":true},{"name":"Charger","packed":false}]flowchart LR
Start["Page opens"] --> Loading["Loading indicator"]
Loading --> Read{"Read and decode stored value"}
Read -->|"Key absent"| Empty["Editable empty list"]
Read -->|"Valid JSON"| Loaded["Editable saved list"]
Read -->|"Read or decode error"| Retry["Error screen with Retry"]
Retry --> LoadingThe screen owns the draft text and current list. The store owns the key, JSON conversion, and plugin calls. The form trims names and rejects whitespace-only input. During a save the screen disables editing, which prevents overlapping writes based on stale copies. If reading fails, it offers Retry before enabling changes so a failed read cannot silently overwrite the saved list.
Preferences are suitable for this small, noncritical list. The plugin can return before a write reaches disk. A larger app that needs transactions or queries can use SQLite. Secrets such as authentication tokens require storage designed for sensitive data.
Shared preferences API and guarantees · Flutter persistence recipes
Assemble the complete app
In the generated pack_list folder, replace the files below and add lib/packing_store.dart. The generated Android and iOS folders contain the native runner projects. Keep them in place. Use a stable Flutter SDK with Dart 3.13 or later and an Android device or emulator compatible with the dependencies.
pubspec.yaml
The manifest declares the app name, SDK range, and dependencies. Keep the package name as pack_list so the test imports resolve.
name: pack_list
description: An offline Flutter packing checklist for beginners.
publish_to: 'none'
version: 1.0.0+1
environment:
sdk: ^3.13.0
dependencies:
flutter:
sdk: flutter
material_ui: 1.11.0
shared_preferences: 2.5.6
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^6.0.0
flutter:
uses-material-design: trueanalysis_options.yaml
include: package:flutter_lints/flutter.yamllib/packing_store.dart
Read PackingItem.toJson() and PackingItem.fromJson() together. They use the same property names. PreferencesPackingStore.load() treats a missing key as the first launch and lets read or decode failures reach the screen.
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
class PackingItem {
const PackingItem(this.name, {this.packed = false});
final String name;
final bool packed;
factory PackingItem.fromJson(Map<String, dynamic> json) {
return PackingItem(json['name'] as String, packed: json['packed'] as bool);
}
Map<String, Object> toJson() => {'name': name, 'packed': packed};
}
abstract interface class PackingStore {
Future<List<PackingItem>> load();
Future<void> save(List<PackingItem> items);
}
class PreferencesPackingStore implements PackingStore {
static const _key = 'pack_list_items_v1';
final _preferences = SharedPreferencesAsync();
@override
Future<List<PackingItem>> load() async {
final raw = await _preferences.getString(_key);
if (raw == null) return [];
final rows = jsonDecode(raw) as List<dynamic>;
return rows
.map((row) => PackingItem.fromJson(row as Map<String, dynamic>))
.toList();
}
@override
Future<void> save(List<PackingItem> items) {
final rows = items.map((item) => item.toJson()).toList();
return _preferences.setString(_key, jsonEncode(rows));
}
}lib/main.dart
Follow main() into PackListApp, then into PackingPage. In _checklist(), index zero holds the form. Each later index maps to an item by subtracting one. _save() is shared by add, toggle, and delete.
import 'package:material_ui/material_ui.dart';
import 'packing_store.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(PackListApp(store: PreferencesPackingStore()));
}
class PackListApp extends StatelessWidget {
const PackListApp({super.key, required this.store});
final PackingStore store;
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Pack List',
theme: ThemeData(colorSchemeSeed: Colors.teal),
home: PackingPage(store: store),
);
}
}
class PackingPage extends StatefulWidget {
const PackingPage({super.key, required this.store});
final PackingStore store;
@override
State<PackingPage> createState() => _PackingPageState();
}
class _PackingPageState extends State<PackingPage> {
final _form = GlobalKey<FormState>();
final _name = TextEditingController();
List<PackingItem>? _items;
bool _loading = true;
bool _saving = false;
@override
void initState() {
super.initState();
_load();
}
@override
void dispose() {
_name.dispose();
super.dispose();
}
Future<void> _load() async {
List<PackingItem>? items;
try {
items = await widget.store.load();
} on Exception {
// A failed read must not turn into an editable empty checklist.
} on TypeError {
// A stored JSON value can have the wrong shape.
}
if (!mounted) return;
setState(() {
_items = items;
_loading = false;
});
}
void _retryLoad() {
setState(() => _loading = true);
_load();
}
Future<void> _save(List<PackingItem> next, {bool clearName = false}) async {
if (_saving) return;
setState(() => _saving = true);
try {
await widget.store.save(next);
if (!mounted) return;
setState(() => _items = next);
if (clearName) _name.clear();
} on Exception {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Could not save. Please try again.')),
);
} finally {
if (mounted) setState(() => _saving = false);
}
}
void _add() {
if (_saving || !_form.currentState!.validate()) return;
_save([..._items!, PackingItem(_name.text.trim())], clearName: true);
}
@override
Widget build(BuildContext context) {
final items = _items;
return Scaffold(
appBar: AppBar(title: const Text('Pack List')),
body: SafeArea(
child: _loading
? const Center(child: CircularProgressIndicator())
: items == null
? Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text('Could not load the packing list.'),
TextButton(
onPressed: _retryLoad,
child: const Text('Retry'),
),
],
),
)
: _checklist(items),
),
);
}
Widget _checklist(List<PackingItem> items) {
final packed = items.where((item) => item.packed).length;
return ListView.builder(
padding: const EdgeInsets.all(16),
itemCount: items.length + 1,
itemBuilder: (context, index) {
if (index == 0) {
return Form(
key: _form,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text('$packed of ${items.length} packed'),
if (_saving) const LinearProgressIndicator(),
TextFormField(
controller: _name,
enabled: !_saving,
maxLength: 80,
decoration: const InputDecoration(labelText: 'Item name'),
textInputAction: TextInputAction.done,
onFieldSubmitted: (_) => _add(),
validator: (value) => (value ?? '').trim().isEmpty
? 'Enter an item name.'
: null,
),
FilledButton(
onPressed: _saving ? null : _add,
child: const Text('Add item'),
),
if (items.isEmpty) const Text('Your packing list is empty.'),
],
),
);
}
final itemIndex = index - 1;
final item = items[itemIndex];
return Row(
children: [
Expanded(
child: CheckboxListTile(
title: Text(item.name),
value: item.packed,
onChanged: _saving
? null
: (checked) {
final next = [...items];
next[itemIndex] = PackingItem(
item.name,
packed: checked ?? false,
);
_save(next);
},
),
),
IconButton(
tooltip: 'Delete ${item.name}',
onPressed: _saving
? null
: () => _save([...items]..removeAt(itemIndex)),
icon: const Icon(Icons.delete_outline),
),
],
);
},
);
}
}test/widget_test.dart
Replace the generated counter test. This test supplies an in-memory store and drives the actual widgets with taps and text entry. Recreating the screen checks that it loads from the supplied store. A device walkthrough checks the native plugin and disk persistence.
import 'package:flutter_test/flutter_test.dart';
import 'package:material_ui/material_ui.dart';
import 'package:pack_list/main.dart';
import 'package:pack_list/packing_store.dart';
class MemoryPackingStore implements PackingStore {
List<PackingItem> items = [];
bool failSave = false;
@override
Future<List<PackingItem>> load() async => [...items];
@override
Future<void> save(List<PackingItem> next) async {
if (failSave) throw Exception('Simulated write failure');
items = [...next];
}
}
void main() {
testWidgets('validates, adds, packs, reloads, and deletes', (tester) async {
final store = MemoryPackingStore();
await tester.pumpWidget(PackListApp(store: store));
await tester.pumpAndSettle();
await tester.tap(find.text('Add item'));
await tester.pumpAndSettle();
expect(find.text('Enter an item name.'), findsOneWidget);
await tester.enterText(find.byType(TextFormField), ' Passport ');
await tester.tap(find.text('Add item'));
await tester.pumpAndSettle();
expect(find.text('0 of 1 packed'), findsOneWidget);
await tester.tap(find.byType(Checkbox));
await tester.pumpAndSettle();
expect(find.text('1 of 1 packed'), findsOneWidget);
await tester.pumpWidget(const SizedBox.shrink());
await tester.pumpWidget(PackListApp(store: store));
await tester.pumpAndSettle();
expect(find.text('1 of 1 packed'), findsOneWidget);
await tester.tap(find.byTooltip('Delete Passport'));
await tester.pumpAndSettle();
expect(find.text('Your packing list is empty.'), findsOneWidget);
expect(store.items, isEmpty);
});
testWidgets('a failed save leaves the form and checklist intact', (
tester,
) async {
final store = MemoryPackingStore()..failSave = true;
await tester.pumpWidget(PackListApp(store: store));
await tester.pumpAndSettle();
await tester.enterText(find.byType(TextFormField), 'Charger');
await tester.tap(find.text('Add item'));
await tester.pumpAndSettle();
expect(find.text('Could not save. Please try again.'), findsOneWidget);
expect(find.text('Charger'), findsOneWidget);
expect(find.text('0 of 0 packed'), findsOneWidget);
store.failSave = false;
await tester.tap(find.text('Add item'));
await tester.pumpAndSettle();
expect(find.text('0 of 1 packed'), findsOneWidget);
});
}Test, debug, and build
flutter pub get
flutter analyze
flutter test
flutter run- Launch on the emulator. Tap Add item with an empty field. Expect a validation message and zero items.
- Add Passport and Charger. Check off Passport and expect 1 of 2 packed. Open the keyboard again and scroll to verify the screen still fits.
- Stop the running app, keep it installed, enable airplane mode, and launch it again. Expect both items and the saved check mark. Delete Charger, relaunch, and expect 1 of 1 packed.
- Repeat with larger system text. Confirm that the checklist remains scrollable and the delete control has a useful spoken label in TalkBack or VoiceOver.
If Flutter sees no Android device, boot the emulator completely and rerun flutter doctor -v and flutter devices. If a plugin is missing after adding it, stop the app, run flutter pub get, and launch it again. If the layout overflows, open Flutter DevTools, inspect the widget tree, and check the parent's constraints and the available screen height.
Debug mode supports hot reload and inspection. Use profile mode on a physical device to investigate performance. For distribution, configure signing and build an Android App Bundle with flutter build appbundle or an iOS archive on a Mac with flutter build ipa. Each store has its own submission and signing workflow.
Testing Flutter apps · DevTools · Android release · iOS release