COMPLETE FLUTTER COURSE · BRAINBIT INFOTECH

Part 5

4 modules · 19 class hours · 40 practical examples

Module 17: Clean Code and App Architecture

Structure apps so they stay easy to change · 4 h

Module 18: Device Features: Share, Camera, Location, Maps

Use the phone hardware and other apps · 4 h

Module 19: Testing, Performance and Release

Prove it works, make it fast, ship it · 3 h

Module 20: Capstone Projects and Career

Build real apps, build your portfolio · 8 h

MODULE 17 · PART 5

Clean Code and App Architecture

Structure apps so they stay easy to change
You will learn
  • Organise folders so anyone can find code
  • Separate models, services and UI
  • Make reusable widgets and constants
  • Use repositories and MVVM with Provider
  • Build a mini clean-architecture app
You will build: a feature-first todo app
4 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
🏗

Where is this used in real apps?

A 200-line app in one file is fine. A 20,000-line app in one file is a disaster. Architecture is how a team of 5 can work on the same app without breaking each other.

Folders

models, services, screens, widgets: you always know where to look.

Separation

UI shows, models hold data, services talk to servers.

Reuse

One AppButton widget used in 40 places: change it once.

lib/
📁
models / user.dart
data classes
📁
services / api.dart
network + storage
📁
screens / home.dart
pages

A sensible folder structure

Group files by what they are (layer-first) or by feature (feature-first: auth/, cart/, profile/). Small apps: layer-first. Big apps: feature-first.

These slides run one file, so each example marks the real file name in a comment, like // lib/models/user.dart.
lib/
  main.dart                 // starts the app
  app.dart                  // MaterialApp, theme, routes
  core/
    constants.dart          // colours, strings, api url
    theme.dart
  models/
    user.dart               // data classes + fromJson
  services/
    api_service.dart        // http calls
    storage_service.dart    // SharedPreferences / SQLite
  repositories/
    user_repository.dart    // decides: cache or network?
  providers/ (or viewmodels/)
    user_provider.dart      // ChangeNotifier
  screens/
    home_screen.dart
    login_screen.dart
  widgets/
    app_button.dart         // reusable pieces

Layers: who talks to whom

UI (screens, widgets)

Shows data, reacts to taps. No http calls here.

State (providers / viewmodels)

Holds screen data and logic. Calls the repository.

Repository

One place that decides where data comes from: network, cache or database.

Service

Does the real work: http, SQLite, Firebase.

Model

Plain data classes used by every layer.

Rule: a layer only talks to the layer directly below it. UI never calls http directly.

Constants and theme

Never type the same colour, text or URL in many places. Put it in one class with static const. Changing the API address becomes a one-line edit.

Bonus: a single place for text makes translation to Hindi much easier.
// lib/core/constants.dart
class AppColors {
  static const primary = Color(0xFF3F51B5);
  static const danger = Color(0xFFD32F2F);
}
class AppText {
  static const appName = 'Ranchi Mart';
  static const currency = 'Rs ';
}
class Api {
  static const baseUrl = 'https://api.brainbit-teaching.com';
}

// use anywhere
Text('${AppText.currency}499', style: const TextStyle(color: AppColors.primary))

Reusable widgets

If you copy-paste a widget three times, make it a class. Parameters (label, onTap, danger) make it flexible. One fix updates every screen.

Rule of three: second time you copy, think. Third time, extract a widget.
// lib/widgets/app_button.dart
class AppButton extends StatelessWidget {
  final String label;
  final VoidCallback onTap;
  final bool danger;
  const AppButton({super.key, required this.label, required this.onTap, this.danger = false});

  @override
  Widget build(BuildContext context) => SizedBox(
    width: double.infinity,
    child: ElevatedButton(
      style: ElevatedButton.styleFrom(backgroundColor: danger ? Colors.red : Colors.indigo, foregroundColor: Colors.white),
      onPressed: onTap, child: Text(label)),
  );
}
// use: AppButton(label: 'Pay', onTap: pay)

MVVM with Provider

Model

Data and rules (Student, Fee).

View

The widgets. Only show things.

ViewModel

A ChangeNotifier that prepares data for the view and handles actions.

Result

You can test the ViewModel without any UI, and redesign the View without touching logic.

Provider + ChangeNotifier from Module 13 is already MVVM. A ViewModel is just a model class with a screen in mind.

Animated explainer: Layers of a clean app

Press Next to walk through it step by step, or Auto play.

Animated explainer: Why separate code?

Press Next to walk through it step by step, or Auto play.
EASYReal project: one place for colours, text and URLsExample 1 of 10

Constants and theme

All colours and texts come from AppColors and AppText. Change the primary colour in one line and the whole screen changes.
// lib/core/constants.dart
class AppColors { static const primary = Color(0xFF00897B); static const accent = Color(0xFFFFA000); }
class AppText { static const name = 'Ranchi Mart'; static const tagline = 'Fresh every morning'; }

// lib/main.dart
void main() => runApp(MaterialApp(
  theme: ThemeData(colorSchemeSeed: AppColors.primary),
  home: Scaffold(
    appBar: AppBar(title: const Text(AppText.name), backgroundColor: AppColors.primary, foregroundColor: Colors.white),
    body: const Center(child: Text(AppText.tagline, style: TextStyle(fontSize: 24, color: AppColors.accent))),
  ),
));
Try it yourself: Change primary to Color(0xFF3949AB).
Edit one line in AppColors.
EASYReal project: User, Product, Order in models/Example 2 of 10

Data model class

A model holds the fields and small rules (like isAdult). Screens never guess Map keys again.
// lib/models/student.dart
class Student {
  final String name;
  final int age;
  final String city;
  const Student({required this.name, required this.age, required this.city});

  bool get isAdult => age >= 18;
  String get label => '$name ($city)';
  factory Student.fromJson(Map<String, dynamic> j) => Student(name: j['name'], age: j['age'], city: j['city']);
  Map<String, dynamic> toJson() => {'name': name, 'age': age, 'city': city};
}

void main() {
  final s = Student.fromJson({'name': 'Asha', 'age': 17, 'city': 'Ranchi'});
  print(s.label);
  print('Adult? ${s.isAdult}');
  print(s.toJson());
}
Try it yourself: Add a "marks" field and print it.
Add it to the constructor, fromJson and toJson.
EASYReal project: services/api_service.dartExample 3 of 10

Service class

A service does one job: here it returns product data. Screens ask the service, they do not know how the data is made. Later you can swap the fake list for a real API.
// lib/services/product_service.dart
class ProductService {
  Future<List<Map<String, dynamic>>> fetchAll() async {
    await Future.delayed(const Duration(milliseconds: 300));   // pretend network
    return [
      {'name': 'School Bag', 'price': 649},
      {'name': 'Water Bottle', 'price': 199},
    ];
  }
}

Future<void> main() async {
  final service = ProductService();
  final items = await service.fetchAll();
  for (final i in items) { print('${i['name']} - Rs ${i['price']}'); }
}
Try it yourself: Add a third product.
Add a Map to the list.
EASYReal project: widgets/app_button.dartExample 4 of 10

Reusable AppButton

AppButton is written once and used three times with different parameters. Change the button style in one place and all three change.
// lib/widgets/app_button.dart
class AppButton extends StatelessWidget {
  final String label; final IconData? icon; final bool danger; final VoidCallback onTap;
  const AppButton({super.key, required this.label, required this.onTap, this.icon, this.danger = false});
  @override
  Widget build(BuildContext context) => Padding(
    padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 6),
    child: SizedBox(width: double.infinity, child: ElevatedButton.icon(
      style: ElevatedButton.styleFrom(backgroundColor: danger ? Colors.red : Colors.indigo, foregroundColor: Colors.white, padding: const EdgeInsets.all(14)),
      onPressed: onTap, icon: Icon(icon ?? Icons.check), label: Text(label))),
  );
}

void main() => runApp(MaterialApp(home: Scaffold(body: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
  AppButton(label: 'Pay now', icon: Icons.payment, onTap: () {}),
  AppButton(label: 'Add to cart', icon: Icons.add_shopping_cart, onTap: () {}),
  AppButton(label: 'Delete account', icon: Icons.delete, danger: true, onTap: () {}),
]))));
Try it yourself: Make the buttons green instead of indigo.
Colors.green in styleFrom.
EASYReal project: widgets/product_card.dartExample 5 of 10

Reusable ProductCard

A ProductCard widget takes a name and a price. The page just lists them. A designer can restyle the card without touching the page.
// lib/widgets/product_card.dart
class ProductCard extends StatelessWidget {
  final String name; final int price;
  const ProductCard({super.key, required this.name, required this.price});
  @override
  Widget build(BuildContext context) => Card(margin: const EdgeInsets.fromLTRB(14, 8, 14, 0),
    child: ListTile(leading: const Icon(Icons.inventory_2, color: Colors.indigo), title: Text(name), trailing: Text('Rs $price', style: const TextStyle(color: Colors.green, fontSize: 16))));
}

// lib/screens/shop_screen.dart
void main() => runApp(MaterialApp(home: Scaffold(
  appBar: AppBar(title: const Text('Shop')),
  body: ListView(children: const [
    ProductCard(name: 'School Bag', price: 649), ProductCard(name: 'Water Bottle', price: 199), ProductCard(name: 'Notebook Set', price: 120),
  ]),
)));
Try it yourself: Add a stock text "In stock" under the name (subtitle).
subtitle: Text('In stock')
MEDIUMReal project: repositories/ folderExample 6 of 10

Repository: cache or network

The repository hides where data comes from. First call is "network" and slow; the second call returns the cached copy. The screen only calls getProducts().
// lib/repositories/product_repository.dart
class ProductRepository {
  List<String>? _cache;
  int networkCalls = 0;

  Future<List<String>> getProducts() async {
    if (_cache != null) { print('  (from cache)'); return _cache!; }
    print('  (from network)');
    networkCalls++;
    await Future.delayed(const Duration(milliseconds: 300));
    _cache = ['School Bag', 'Water Bottle', 'Notebook Set'];
    return _cache!;
  }
}

Future<void> main() async {
  final repo = ProductRepository();
  print('First call:');
  print(await repo.getProducts());
  print('Second call:');
  print(await repo.getProducts());
  print('Network calls made: ${repo.networkCalls}');
}
Try it yourself: Add a refresh() method that clears the cache.
void refresh() { _cache = null; }
MEDIUMReal project: ViewModel + ViewExample 7 of 10

MVVM with Provider

StudentViewModel owns the list and the loading flag. The View only reads them and calls load(). No logic in the widget.
import 'package:provider/provider.dart';
// lib/viewmodels/student_vm.dart
class StudentVM extends ChangeNotifier {
  List<String> students = [];
  bool loading = false;
  Future<void> load() async {
    loading = true; notifyListeners();
    await Future.delayed(const Duration(milliseconds: 600));
    students = ['Asha Kumari', 'Rohit Singh', 'Pooja Sahu'];
    loading = false; notifyListeners();
  }
}

// lib/views/student_view.dart
class StudentView extends StatelessWidget {
  const StudentView({super.key});
  @override
  Widget build(BuildContext context) {
    final vm = context.watch<StudentVM>();
    return Scaffold(
      appBar: AppBar(title: const Text('Students')),
      body: vm.loading ? const Center(child: CircularProgressIndicator())
          : ListView(children: vm.students.map((s) => ListTile(title: Text(s))).toList()),
      floatingActionButton: FloatingActionButton(onPressed: () => context.read<StudentVM>().load(), child: const Icon(Icons.download)),
    );
  }
}
void main() => runApp(ChangeNotifierProvider(create: (_) => StudentVM(), child: const MaterialApp(home: StudentView())));
Try it yourself: Add an "error" string to the ViewModel.
String? error; set it in a try/catch.
MEDIUMReal project: swap real and fake servicesExample 8 of 10

Dependency injection

The ViewModel does not create its service, it receives it. In production we give the real API. In tests or demos we give a fake. Nothing else changes.
abstract class ProductSource {
  Future<List<String>> load();
}
class ApiSource implements ProductSource {
  Future<List<String>> load() async => ['(from the real server)'];
}
class FakeSource implements ProductSource {
  Future<List<String>> load() async => ['School Bag', 'Water Bottle'];
}

class ShopViewModel {
  final ProductSource source;          // injected, not created here
  ShopViewModel(this.source);
  Future<void> show() async { print((await source.load()).join(', ')); }
}

Future<void> main() async {
  await ShopViewModel(FakeSource()).show();
  await ShopViewModel(ApiSource()).show();
}
Try it yourself: Add a third source "SqliteSource".
Another class that implements ProductSource.
HARDReal project: how real teams organise featuresExample 9 of 10

Feature-first todo app

The todo feature keeps model, service, viewmodel and view together, and uses the shared AppButton and constants. Everything about todos is in one folder: easy to find, easy to delete.
import 'package:provider/provider.dart';
// lib/core/app_colors.dart
const kPrimary = Colors.indigo;

// lib/features/todo/todo_model.dart
class Todo { final String title; bool done; Todo(this.title, [this.done = false]); }

// lib/features/todo/todo_service.dart (pretend storage)
class TodoService {
  final List<Todo> _db = [Todo('Revise architecture'), Todo('Push code to GitHub')];
  Future<List<Todo>> all() async => List.of(_db);
  Future<void> add(String t) async => _db.add(Todo(t));
}

// lib/features/todo/todo_vm.dart
class TodoVM extends ChangeNotifier {
  final TodoService service;
  TodoVM(this.service) { load(); }
  List<Todo> items = [];
  int get doneCount => items.where((t) => t.done).length;
  Future<void> load() async { items = await service.all(); notifyListeners(); }
  Future<void> add(String t) async { await service.add(t); await load(); }
  void toggle(Todo t) { t.done = !t.done; notifyListeners(); }
}

// lib/features/todo/todo_view.dart
class TodoView extends StatelessWidget {
  const TodoView({super.key});
  @override
  Widget build(BuildContext context) {
    final vm = context.watch<TodoVM>();
    return Scaffold(
      appBar: AppBar(title: Text('Todos ${vm.doneCount}/${vm.items.length}'), backgroundColor: kPrimary, foregroundColor: Colors.white),
      body: ListView(children: vm.items.map((t) => CheckboxListTile(title: Text(t.title), value: t.done, onChanged: (_) => vm.toggle(t))).toList()),
      floatingActionButton: FloatingActionButton(onPressed: () => vm.add('New task ${vm.items.length + 1}'), child: const Icon(Icons.add)),
    );
  }
}
void main() => runApp(ChangeNotifierProvider(create: (_) => TodoVM(TodoService()), child: const MaterialApp(home: TodoView())));
Try it yourself: Add a remove() method to the ViewModel and a delete icon.
service removes it; view calls vm.remove(t).
HARDReal project: a layered app with clear boundariesExample 10 of 10

Mini clean architecture

Four layers in one run: entity (Product), repository interface, use case (apply discount) and UI. The use case contains the business rule, so it can be tested alone and reused by any screen.
// domain/product.dart
class Product { final String name; final int price; const Product(this.name, this.price); }

// domain/product_repository.dart
abstract class ProductRepository { List<Product> all(); }

// data/in_memory_repository.dart
class InMemoryRepository implements ProductRepository {
  List<Product> all() => const [Product('School Bag', 649), Product('Water Bottle', 199), Product('Notebooks', 120)];
}

// domain/get_offer_prices.dart  (use case: the business rule)
class GetOfferPrices {
  final ProductRepository repo;
  GetOfferPrices(this.repo);
  List<Product> execute(int percentOff) => repo.all().map((p) => Product(p.name, (p.price * (100 - percentOff) ~/ 100))).toList();
}

// ui/offer_screen.dart
class OfferScreen extends StatelessWidget {
  final GetOfferPrices useCase;
  const OfferScreen(this.useCase, {super.key});
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Diwali Offer: 20% off')),
    body: ListView(children: useCase.execute(20).map((p) => ListTile(title: Text(p.name), trailing: Text('Rs ${p.price}', style: const TextStyle(color: Colors.green)))).toList()),
  );
}
void main() => runApp(MaterialApp(home: OfferScreen(GetOfferPrices(InMemoryRepository()))));
Try it yourself: Change the offer to 30 percent.
useCase.execute(30) and the title text.

Quick quiz

3 questions. Click an answer.
Where should http calls live?
Inside build()In a service classIn pubspec.yamlIn an Icon
What does a repository decide?
Which colour to useWhere data comes from (cache or network)Which font to useHow to animate
When should you extract a widget into its own class?
NeverWhen you reuse it or it grows bigOnly for buttonsOnly in tests
Score: 0 / 3

Recap: what you learned in Module 17

Folders

models, services, repositories, screens, widgets.

Layers

UI > ViewModel > Repository > Service.

Constants

One place for colours, texts, URLs.

Reuse

AppButton, ProductCard.

MVVM

ViewModel holds state and logic.

Injection

Pass dependencies in, so they can be swapped.

Next: Device Features: Share, Camera, Location, Maps - Use the phone hardware and other apps
MODULE 18 · PART 5

Device Features: Share, Camera, Location, Maps

Use the phone hardware and other apps
You will learn
  • Open links, calls and WhatsApp with url_launcher
  • Share text and copy to clipboard
  • Pick photos and ask for permissions
  • Read the GPS location and show it on a map
  • Show notifications and generate QR codes
You will build: a camera attendance app
4 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
📱

Where is this used in real apps?

A Flutter app is not locked inside its own screen. It can call a customer, open Google Maps, share an invoice on WhatsApp, take a photo and know where the user is.

Plugins

Packages that give Flutter access to the phone: camera, GPS, contacts, sensors.

Permissions

The user must allow camera or location. Always ask politely and explain why.

Real uses

Delivery tracking, field-staff attendance with selfie and GPS, share receipt on WhatsApp.

Attendance
📷
Selfie taken
9:02 AM
📍
Location
23.34 N, 85.31 E
✅
Marked present
Namkum Office

How plugins work

Flutter code cannot talk to the camera by itself. A plugin contains small Android and iOS code and gives you easy Dart functions. You add it to pubspec.yaml, then import it.

Find plugins

pub.dev: search, check likes, pub points and recent updates.

Add

flutter pub add url_launcher

Platform setup

Many plugins need a line in AndroidManifest.xml or Info.plist (permissions).

Simulated here

These slides simulate plugins inside the browser. The Dart code is real; the phone parts are pretend.

Honest note: in these slides the camera, GPS and share sheet are simulated. On a real phone they open the real thing.

url_launcher and share

Four useful URL schemes: https: (web), tel: (dial), mailto: (email), geo: (map). On Android 11+ add <queries> to the manifest.

Real use: "Call us", "WhatsApp us" and "Get directions" buttons on every business app.
import 'package:url_launcher/url_launcher.dart';
import 'package:share_plus/share_plus.dart';

// open a website
await launchUrl(Uri.parse('https://brainbit-teaching.com'), mode: LaunchMode.externalApplication);

// call a number
await launchUrl(Uri.parse('tel:+919876543210'));

// open WhatsApp chat
await launchUrl(Uri.parse('https://wa.me/919876543210?text=Hello'));

// open Google Maps
await launchUrl(Uri.parse('geo:23.3441,85.3096'));

// share text with any app
await Share.share('Fee receipt 1042: Rs 12,000 paid');

Permissions

Dangerous features need the user's permission: camera, location, contacts, notifications. Ask when needed, not at app start, and show a friendly reason first.

Also add the permission line to AndroidManifest.xml, for example android.permission.CAMERA.
import 'package:permission_handler/permission_handler.dart';

final status = await Permission.camera.status;

if (status.isGranted) {
  openCamera();
} else {
  final r = await Permission.camera.request();   // shows the system dialog
  if (r.isGranted) openCamera();
  else if (r.isPermanentlyDenied) openAppSettings();
}

Image picker and location

pickImage returns the file path of the photo (or null if the user cancelled). getCurrentPosition gives latitude and longitude. Both are async and need permissions.

Always handle null: the user can press back and take no photo.
import 'package:image_picker/image_picker.dart';
import 'package:geolocator/geolocator.dart';

// photo from camera or gallery
final XFile? photo = await ImagePicker().pickImage(source: ImageSource.camera);
print(photo?.path);

// GPS position
final pos = await Geolocator.getCurrentPosition();
print('${pos.latitude}, ${pos.longitude}');

Maps, notifications and QR

google_maps_flutter

Shows a Google map with markers. Needs a Maps API key in the manifest.

flutter_local_notifications

Shows a notification at a time you choose: reminders, alarms.

qr_flutter

QrImageView(data: text, size: 200) draws a QR code from any text: UPI, ticket, attendance.

mobile_scanner

Reads QR codes with the camera.

Real use: shop QR for UPI payment, class attendance QR, event entry pass.

Animated explainer: Asking for a permission

Press Next to walk through it step by step, or Auto play.

Animated explainer: Attendance with photo and GPS

Press Next to walk through it step by step, or Auto play.
EASYReal project: contact buttons on a business appExample 1 of 10

Open a link, call, WhatsApp

launchUrl opens other apps using a URL scheme. On a phone these open the browser, dialler and WhatsApp. In the slides a message shows what would open.
import 'package:url_launcher/url_launcher.dart';

class Page extends StatefulWidget {
  const Page({super.key});
  @override
  State<Page> createState() => _PageState();
}
class _PageState extends State<Page> {

  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Contact us')),
    body: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
      ListTile(leading: const Icon(Icons.language), title: const Text('Visit website'), onTap: () => launchUrl(Uri.parse('https://brainbit-teaching.com'))),
      ListTile(leading: const Icon(Icons.call), title: const Text('Call us'), onTap: () => launchUrl(Uri.parse('tel:+919876543210'))),
      ListTile(leading: const Icon(Icons.chat), title: const Text('WhatsApp'), onTap: () => launchUrl(Uri.parse('https://wa.me/919876543210?text=Hello'))),
      ListTile(leading: const Icon(Icons.map), title: const Text('Directions'), onTap: () => launchUrl(Uri.parse('geo:23.3441,85.3096'))),
    ]),
  );
}
void main() => runApp(const MaterialApp(home: Page()));
Try it yourself: Add an email tile with mailto:info@brainbit-teaching.com.
launchUrl(Uri.parse('mailto:info@brainbit-teaching.com'))
EASYReal project: share bill or result on WhatsAppExample 2 of 10

Share a receipt

Share.share(text) opens the phone share sheet so the user can pick WhatsApp, Gmail or any app. One line, big effect.
import 'package:share_plus/share_plus.dart';

class Page extends StatefulWidget {
  const Page({super.key});
  @override
  State<Page> createState() => _PageState();
}
class _PageState extends State<Page> {

  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Fee receipt')),
    body: Padding(padding: const EdgeInsets.all(20), child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
      const Icon(Icons.receipt_long, size: 70, color: Colors.indigo),
      const Text('Receipt 1042', style: TextStyle(fontSize: 24)),
      const Text('Rohit Singh paid Rs 12,000'),
      const SizedBox(height: 16),
      ElevatedButton.icon(onPressed: () => Share.share('Receipt 1042: Rohit Singh paid Rs 12,000 at BrainBit Infotech, Ranchi'), icon: const Icon(Icons.share), label: const Text('Share')),
    ])),
  );
}
void main() => runApp(const MaterialApp(home: Page()));
Try it yourself: Change the amount to Rs 9,500.
Edit the Text and the share text.
EASYReal project: copy referral code or UPI idExample 3 of 10

Copy to clipboard

Clipboard.setData copies text so the user can paste it elsewhere. Always show a small confirmation.
import 'package:flutter/services.dart';

class Page extends StatefulWidget {
  const Page({super.key});
  @override
  State<Page> createState() => _PageState();
}
class _PageState extends State<Page> {

  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Refer and earn')),
    body: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
      const Text('Your referral code'),
      Container(padding: const EdgeInsets.all(14), margin: const EdgeInsets.all(12), color: Colors.amber.shade100, child: const Text('RANCHI-2026', style: TextStyle(fontSize: 26, letterSpacing: 2))),
      ElevatedButton.icon(onPressed: () async {
        await Clipboard.setData(const ClipboardData(text: 'RANCHI-2026'));
        ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Code copied')));
      }, icon: const Icon(Icons.content_copy), label: const Text('Copy')),
    ])),
  );
}
void main() => runApp(const MaterialApp(home: Page()));
Try it yourself: Copy a UPI id instead: brainbit@upi.
ClipboardData(text: 'brainbit@upi')
EASYReal project: before camera, GPS, notificationsExample 4 of 10

Ask for a permission

Check the status first, request if needed and show the result. The user may refuse, so handle both paths.
import 'package:permission_handler/permission_handler.dart';

class Page extends StatefulWidget {
  const Page({super.key});
  @override
  State<Page> createState() => _PageState();
}
class _PageState extends State<Page> {
  String msg = 'Camera: not asked yet';
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Permissions')),
    body: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
      Text(msg, style: const TextStyle(fontSize: 20)),
      const SizedBox(height: 12),
      ElevatedButton(onPressed: () async {
        final r = await Permission.camera.request();
        setState(() => msg = r.isGranted ? 'Camera allowed' : 'Camera denied');
      }, child: const Text('Allow camera')),
    ])),
  );
}
void main() => runApp(const MaterialApp(home: Page()));
Try it yourself: Add a second button for location.
Permission.location.request()
EASYReal project: UPI QR, tickets, attendance QRExample 5 of 10

QR code generator

QrImageView turns any text into a QR code live as you type. Shops use this for payments and events use it for passes. The picture here is a simulated QR.
import 'package:qr_flutter/qr_flutter.dart';

class Page extends StatefulWidget {
  const Page({super.key});
  @override
  State<Page> createState() => _PageState();
}
class _PageState extends State<Page> {
  String data = 'upi://pay?pa=brainbit@upi&am=500';
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('My QR')),
    body: Padding(padding: const EdgeInsets.all(20), child: Column(children: [
      TextField(onChanged: (v) => setState(() => data = v), decoration: const InputDecoration(labelText: 'Text for the QR', border: OutlineInputBorder())),
      const SizedBox(height: 20),
      QrImageView(data: data, size: 180),
      const SizedBox(height: 8),
      Text(data),
    ])),
  );
}
void main() => runApp(const MaterialApp(home: Page()));
Try it yourself: Show the QR in a Card with padding.
Wrap QrImageView in Card(child: Padding(...)).
MEDIUMReal project: profile photo uploadExample 6 of 10

Pick a photo

pickImage returns an XFile with a path, or null if cancelled. You would show it with Image.file(File(path)). Here a placeholder box shows the file name.
import 'package:image_picker/image_picker.dart';

class Page extends StatefulWidget {
  const Page({super.key});
  @override
  State<Page> createState() => _PageState();
}
class _PageState extends State<Page> {
  String? path;
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Profile photo')),
    body: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
      CircleAvatar(radius: 56, child: Text(path == null ? '?' : 'OK', style: const TextStyle(fontSize: 30))),
      const SizedBox(height: 12),
      Text(path ?? 'No photo chosen'),
      Row(mainAxisAlignment: MainAxisAlignment.center, children: [
        TextButton.icon(onPressed: () async { final f = await ImagePicker().pickImage(source: ImageSource.camera); if (f != null) setState(() => path = f.path); }, icon: const Icon(Icons.camera_alt), label: const Text('Camera')),
        TextButton.icon(onPressed: () async { final f = await ImagePicker().pickImage(source: ImageSource.gallery); if (f != null) setState(() => path = f.path); }, icon: const Icon(Icons.photo), label: const Text('Gallery')),
      ]),
    ])),
  );
}
void main() => runApp(const MaterialApp(home: Page()));
Try it yourself: Add a Remove button that sets path to null.
setState(() => path = null)
MEDIUMReal project: delivery, field staff, nearby searchExample 7 of 10

Current location

getCurrentPosition returns latitude and longitude. We also compute the straight-line distance to the Ranchi Railway Station with a simple formula. Location is simulated at Ranchi.
import 'package:geolocator/geolocator.dart';

class Page extends StatefulWidget {
  const Page({super.key});
  @override
  State<Page> createState() => _PageState();
}
class _PageState extends State<Page> {
  String text = 'Location unknown';
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Where am I')),
    body: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
      Text(text, style: const TextStyle(fontSize: 20), textAlign: TextAlign.center),
      const SizedBox(height: 12),
      ElevatedButton.icon(onPressed: () async {
        final p = await Geolocator.getCurrentPosition();
        final dLat = (p.latitude - 23.3569) * 111;
        final dLng = (p.longitude - 85.3340) * 102;
        final km = (dLat * dLat + dLng * dLng);
        setState(() => text = 'Lat ${p.latitude.toStringAsFixed(4)}\nLng ${p.longitude.toStringAsFixed(4)}\nAbout ${km.toStringAsFixed(1)} sq-km units from Ranchi Station');
      }, icon: const Icon(Icons.my_location), label: const Text('Get location')),
    ])),
  );
}
void main() => runApp(const MaterialApp(home: Page()));
Try it yourself: Show the accuracy too (p.accuracy).
p.accuracy.toStringAsFixed(0)
MEDIUMReal project: shop locator, delivery mapExample 8 of 10

Map with markers

GoogleMap takes a starting camera position and a set of Markers. This is a simulated map listing the markers; a real one draws a Google map with pins.
import 'package:google_maps_flutter/google_maps_flutter.dart';

void main() => runApp(MaterialApp(home: Scaffold(
  appBar: AppBar(title: const Text('Our branches')),
  body: GoogleMap(
    initialCameraPosition: const CameraPosition(target: LatLng(23.3441, 85.3096), zoom: 12),
    markers: {
      const Marker(markerId: MarkerId('main'), position: LatLng(23.3441, 85.3096), infoWindow: InfoWindow(title: 'BrainBit Infotech HQ, Ranchi')),
      const Marker(markerId: MarkerId('b2'), position: LatLng(23.3700, 85.3250), infoWindow: InfoWindow(title: 'Kanke Road branch')),
      const Marker(markerId: MarkerId('b3'), position: LatLng(23.3100, 85.2800), infoWindow: InfoWindow(title: 'Namkum branch')),
    },
  ),
)));
Try it yourself: Add a fourth branch at Hatia (23.3000, 85.3400).
Another Marker with a new markerId.
HARDReal project: reminders, fee due alertsExample 9 of 10

Local notification reminder

FlutterLocalNotificationsPlugin shows a notification. Here a reminder is created for a task and a simulated notification pops up. It also needs the notification permission on Android 13+.
import 'package:permission_handler/permission_handler.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

class Page extends StatefulWidget {
  const Page({super.key});
  @override
  State<Page> createState() => _PageState();
}
class _PageState extends State<Page> {
  final plugin = FlutterLocalNotificationsPlugin();
  final tasks = ['Pay electricity bill', 'Submit assignment', 'Renew library card'];
  final done = <String>{};
  Future<void> remind(String t) async {
    final ok = await Permission.notification.request();
    if (!ok.isGranted) return;
    await plugin.show(t.length, 'Reminder', t, null);
    setState(() => done.add(t));
  }
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: Text('Reminders (${done.length})')),
    body: ListView(children: tasks.map((t) => ListTile(
      title: Text(t), subtitle: Text(done.contains(t) ? 'Reminder sent' : 'Not set'),
      trailing: IconButton(icon: Icon(done.contains(t) ? Icons.notifications_active : Icons.notifications_none, color: Colors.orange), onPressed: () => remind(t)),
    )).toList()),
  );
}
void main() => runApp(const MaterialApp(home: Page()));
Try it yourself: Add a fourth task.
Add a string to the tasks list.
HARDReal project: field-staff attendance with selfie and GPSExample 10 of 10

Camera attendance app

Combines the module: ask permissions, take a selfie, read GPS, check the office area and add a record to the attendance log. The same flow as real field-staff apps (location is simulated at Ranchi).
import 'package:image_picker/image_picker.dart';
import 'package:geolocator/geolocator.dart';
import 'package:permission_handler/permission_handler.dart';

class Page extends StatefulWidget {
  const Page({super.key});
  @override
  State<Page> createState() => _PageState();
}
class _PageState extends State<Page> {
  final log = <String>[];
  String status = 'Tap Check in';
  Future<void> checkIn() async {
    final cam = await Permission.camera.request();
    final loc = await Permission.location.request();
    if (!cam.isGranted || !loc.isGranted) { setState(() => status = 'Permissions needed'); return; }
    final photo = await ImagePicker().pickImage(source: ImageSource.camera);
    if (photo == null) { setState(() => status = 'Selfie cancelled'); return; }
    final pos = await Geolocator.getCurrentPosition();
    final inOffice = (pos.latitude - 23.34).abs() < 0.05 && (pos.longitude - 85.31).abs() < 0.05;
    setState(() {
      status = inOffice ? 'Checked in at office' : 'Outside office area';
      log.insert(0, '${photo.name}  ${pos.latitude.toStringAsFixed(3)}, ${pos.longitude.toStringAsFixed(3)}  ${inOffice ? 'OK' : 'FAR'}');
    });
  }
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Attendance')),
    body: Column(children: [
      Container(width: double.infinity, color: Colors.teal.shade50, padding: const EdgeInsets.all(16), child: Text(status, style: const TextStyle(fontSize: 20))),
      ElevatedButton.icon(onPressed: checkIn, icon: const Icon(Icons.camera_alt), label: const Text('Check in')),
      Expanded(child: ListView(children: log.map((l) => ListTile(leading: const Icon(Icons.verified), title: Text(l))).toList())),
    ]),
  );
}
void main() => runApp(const MaterialApp(home: Page()));
Try it yourself: Show the check-in time using DateTime.now().
'${DateTime.now().hour}:${DateTime.now().minute}' in the log line.

Quick quiz

3 questions. Click an answer.
What must you do before opening the camera?
NothingCheck or request the permissionRestart the phoneDelete the cache
Which URL scheme dials a phone number?
https:tel:geo:mailto:
What does pickImage return if the user cancels?
An errornullAn empty listA QR code
Score: 0 / 3

Recap: what you learned in Module 18

Plugins

Packages from pub.dev give access to the phone.

url_launcher

Open web, call, WhatsApp, maps.

Share and clipboard

Share.share and Clipboard.setData.

Permissions

Check, request, handle denial.

Camera and GPS

pickImage and getCurrentPosition.

Maps, notifications, QR

google_maps, local notifications, qr_flutter.

Next: Testing, Performance and Release - Prove it works, make it fast, ship it
MODULE 19 · PART 5

Testing, Performance and Release

Prove it works, make it fast, ship it
You will learn
  • Write unit tests for plain Dart code
  • Write widget tests that tap and check the screen
  • Use debugPrint and DevTools to find bugs
  • Make apps faster with const and small builders
  • Build a signed APK / app bundle and publish
You will build: a tested, release-ready app
3 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
🚀

Where is this used in real apps?

Before you give an app to a customer you must be sure it works and is fast. Tests catch bugs in seconds, while users catch them in one-star reviews.

Tests

Small programs that check your code. Run them after every change.

Performance

Smooth 60 frames per second on a Rs 8,000 phone, not just on your laptop.

Release

Sign the app, build an app bundle, upload to Play Store.

Test results
✅
Unit tests
24 passed
✅
Widget tests
11 passed
🚀
Release build
app-release.aab

Why test?

A test is a small piece of code that runs your code and checks the answer. If you change something and break an old feature, a test fails immediately.

Unit test

Checks one function or class. Very fast.

Widget test

Builds a widget, taps buttons and checks the text on screen.

Integration test

Runs the whole app on a device. Slow, used for key flows.

Run

flutter test in the terminal runs everything in the test/ folder.

Honest note: here the tests run in a simulated engine. The same test code runs on the real Flutter SDK with flutter test.

Your first unit test

test(name, body) defines a test. expect(actual, matcher) compares. Use matchers: equals, isTrue, isNull, contains, hasLength, closeTo, greaterThan.

Tip: change 4500 to 4000 and run again to see a failing test.
import 'package:flutter_test/flutter_test.dart';
int fee(int months) => months * 1500;

void main() {
  test('fee for 3 months', () {
    expect(fee(3), 4500);
  });
  test('fee for 0 months', () {
    expect(fee(0), 0);
  });
}

Your first widget test

pumpWidget shows the widget. find looks for text, icons or types. tap presses it. pump rebuilds the screen after setState.

Pattern: Arrange (build), Act (tap), Assert (expect).
import 'package:flutter_test/flutter_test.dart';
class Counter extends StatefulWidget {
  const Counter({super.key});
  @override
  State<Counter> createState() => _CounterState();
}
class _CounterState extends State<Counter> {
  int n = 0;
  @override
  Widget build(BuildContext context) => Scaffold(
    body: Center(child: Text('$n')),
    floatingActionButton: FloatingActionButton(onPressed: () => setState(() => n++), child: const Icon(Icons.add)),
  );
}
void main() {
  testWidgets('counter goes up', (tester) async {
    await tester.pumpWidget(const MaterialApp(home: Counter()));
    expect(find.text('0'), findsOneWidget);
    await tester.tap(find.byIcon(Icons.add));
    await tester.pump();
    expect(find.text('1'), findsOneWidget);
  });
}

Making apps fast

const

Mark widgets const when they never change. Flutter skips rebuilding them.

Small widgets

Put setState inside a small widget so only that part rebuilds.

ListView.builder

Builds only visible rows. Never use a Column with 1000 children.

Avoid work in build()

No network calls, sorting or heavy loops inside build.

DevTools

The Performance and Widget Inspector tabs show slow frames and rebuild counts.

Rule: measure first with DevTools, then optimise. Do not guess.

Release checklist

App name and icon

Set the label and launcher icon.

Version

version: 1.0.0+1 in pubspec.yaml. Increase +1 for every upload.

Signing key

Create a keystore with keytool and keep it safe. Losing it means you cannot update the app.

Build

flutter build appbundle --release

Play Store

Developer account (one-time USD 25), screenshots, privacy policy, then upload the .aab.

Test the release build on a real phone before uploading. Debug and release can behave differently.

Animated explainer: The test pyramid

Press Next to walk through it step by step, or Auto play.

Animated explainer: From code to Play Store

Press Next to walk through it step by step, or Auto play.
EASYReal project: billing rules in a coaching-fee appExample 1 of 10

Unit test: fee calculator

A unit test calls one function with known input and checks the answer. If someone changes the discount rule by mistake, the test fails at once.
import 'package:flutter_test/flutter_test.dart';
int fee(int months, {bool sibling = false}) {
  final total = months * 1500;
  return sibling ? total - total ~/ 10 : total;
}

void main() {
  test('3 months normal', () => expect(fee(3), 4500));
  test('sibling gets 10% off', () => expect(fee(3, sibling: true), 4050));
  test('zero months', () => expect(fee(0), 0));
}
Try it yourself: Add a test for 12 months with sibling discount (16200).
expect(fee(12, sibling: true), 16200)
EASYReal project: cleaning user input in formsExample 2 of 10

Test a string helper

Small helper functions are the easiest to test. Here we test a function that makes a clean username from a name.
import 'package:flutter_test/flutter_test.dart';
String username(String name) => name.trim().toLowerCase().replaceAll(' ', '_');

void main() {
  test('trims and lowercases', () => expect(username('  Asha Kumari '), 'asha_kumari'));
  test('single word', () => expect(username('Rohit'), 'rohit'));
  test('is not empty', () => expect(username('Pooja Sahu'), isNotEmpty));
}
Try it yourself: Add a test for Vikash Oraon.
expect(username('Vikash Oraon'), 'vikash_oraon')
EASYReal project: checking a button really changes the screenExample 3 of 10

Widget test: counter

A widget test builds the widget, taps the button and checks the text. No phone is needed.
import 'package:flutter_test/flutter_test.dart';
class Counter extends StatefulWidget {
  const Counter({super.key});
  @override
  State<Counter> createState() => _CounterState();
}
class _CounterState extends State<Counter> {
  int n = 0;
  @override
  Widget build(BuildContext context) => Scaffold(
    body: Center(child: Text('$n')),
    floatingActionButton: FloatingActionButton(onPressed: () => setState(() => n++), child: const Icon(Icons.add)),
  );
}
void main() {
  testWidgets('tap + three times', (tester) async {
    await tester.pumpWidget(const MaterialApp(home: Counter()));
    expect(find.text('0'), findsOneWidget);
    for (int i = 0; i < 3; i++) {
      await tester.tap(find.byIcon(Icons.add));
      await tester.pump();
    }
    expect(find.text('3'), findsOneWidget);
  });
}
Try it yourself: Check that text 0 is gone after the taps.
expect(find.text('0'), findsNothing)
EASYReal project: how a test protects you from a bugExample 4 of 10

A failing test (on purpose)

This failure is intentional. The function has a bug (it adds 5% instead of 18% GST). The test catches it. Read the message: Expected vs Actual.
import 'package:flutter_test/flutter_test.dart';
double withGst(double price) => price * 1.05;   // BUG: should be 1.18

void main() {
  test('GST 18% on Rs 1000', () {
    expect(withGst(1000), closeTo(1180, 0.01));
  });
}
Try it yourself: Fix 1.05 to 1.18 and run again.
Change the multiplier.
EASYReal project: finding why a button does nothingExample 5 of 10

debugPrint and print

debugPrint prints only in debug mode and is safe for long text. Print the values you are unsure about, find the wrong one, fix it, then remove the logs.
import 'package:flutter_test/flutter_test.dart';
int total(List<int> prices) {
  var sum = 0;
  for (final p in prices) {
    debugPrint('adding $p, sum was $sum');
    sum += p;
  }
  return sum;
}

void main() {
  final bill = total([120, 80, 250]);
  debugPrint('final bill = $bill');
}
Try it yourself: Add a price 45 to the list.
total([120, 80, 250, 45])
MEDIUMReal project: data classes for students, orders, productsExample 6 of 10

Test a model class

Models hold data and small rules. Test them, and test the fromJson parsing so an API change is caught early.
import 'package:flutter_test/flutter_test.dart';
class Student {
  final String name;
  final int marks;
  Student({required this.name, required this.marks});
  factory Student.fromJson(Map<String, dynamic> j) => Student(name: j['name'], marks: j['marks']);
  String get grade => marks >= 75 ? 'A' : marks >= 50 ? 'B' : 'C';
}

void main() {
  test('fromJson reads fields', () {
    final s = Student.fromJson({'name': 'Asha', 'marks': 82});
    expect(s.name, 'Asha');
    expect(s.marks, 82);
  });
  test('grade A at 75+', () => expect(Student(name: 'X', marks: 75).grade, 'A'));
  test('grade C below 50', () => expect(Student(name: 'Y', marks: 49).grade, 'C'));
}
Try it yourself: Add a test for grade B at exactly 50.
expect(Student(name: 'Z', marks: 50).grade, 'B')
MEDIUMReal project: cart or counter logic without any UIExample 7 of 10

Test a Provider model

A ChangeNotifier is plain Dart, so it can be unit-tested without widgets. We also count notifications to prove the UI would be told.
import 'package:flutter_test/flutter_test.dart';
import 'package:provider/provider.dart';

class Cart extends ChangeNotifier {
  final items = <String, int>{};
  int get total => items.values.fold(0, (a, b) => a + b);
  void add(String name, int price) {
    items[name] = price;
    notifyListeners();
  }
  void clear() { items.clear(); notifyListeners(); }
}

void main() {
  test('add updates total and notifies', () {
    final cart = Cart();
    var calls = 0;
    cart.addListener(() => calls++);
    cart.add('Bag', 519);
    cart.add('Bottle', 159);
    expect(cart.total, 678);
    expect(calls, 2);
  });
  test('clear empties the cart', () {
    final cart = Cart()..add('Pen', 10);
    cart.clear();
    expect(cart.items, isEmpty);
  });
}
Try it yourself: Test that adding the same name twice keeps one item.
expect(cart.items.length, 1)
MEDIUMReal project: scrolling a 1000-item product list smoothlyExample 8 of 10

Faster lists with const and builder

A Column would build all 300 rows at once; ListView.builder builds only what is visible and const widgets are reused. The counter shows how many rows were built: this simulated engine builds about 40 rows, a real phone builds only the 10 or so you can see.
class Page extends StatefulWidget {
  const Page({super.key});
  @override
  State<Page> createState() => _PageState();
}
class _PageState extends State<Page> {
  int built = 0;
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Products (builder)')),
    body: Column(children: [
      Container(width: double.infinity, color: Colors.amber.shade100, padding: const EdgeInsets.all(10), child: Text('Rows built so far: $built of 300')),
      Expanded(child: ListView.builder(
        itemCount: 300,
        itemBuilder: (context, i) {
          if (i + 1 > built) Future.microtask(() { if (mounted && i + 1 > built) setState(() => built = i + 1); });
          return ListTile(leading: const Icon(Icons.shopping_bag), title: Text('Product ${i + 1}'), subtitle: const Text('Rs 199'));
        },
      )),
    ]),
  );
}
void main() => runApp(const MaterialApp(home: Page()));
Try it yourself: Change itemCount to 3000. Built rows stay small.
Only visible rows are built.
HARDReal project: making sure a form shows errors and successExample 9 of 10

Widget test: login form

Type into fields with enterText, tap the button and check the messages. This protects the most important screen of any app.
import 'package:flutter_test/flutter_test.dart';
class Login extends StatefulWidget {
  const Login({super.key});
  @override
  State<Login> createState() => _LoginState();
}
class _LoginState extends State<Login> {
  String email = '';
  String msg = '';
  @override
  Widget build(BuildContext context) => Scaffold(
    body: Column(children: [
      TextField(onChanged: (v) => setState(() => email = v)),
      ElevatedButton(onPressed: () => setState(() => msg = email.contains('@') ? 'Welcome' : 'Enter a valid email'), child: const Text('Login')),
      Text(msg),
    ]),
  );
}

void main() {
  testWidgets('invalid email shows error', (tester) async {
    await tester.pumpWidget(const MaterialApp(home: Login()));
    await tester.enterText(find.byType(TextField), 'asha');
    await tester.tap(find.text('Login'));
    await tester.pump();
    expect(find.text('Enter a valid email'), findsOneWidget);
  });
  testWidgets('valid email says welcome', (tester) async {
    await tester.pumpWidget(const MaterialApp(home: Login()));
    await tester.enterText(find.byType(TextField), 'asha@ranchi.in');
    await tester.tap(find.text('Login'));
    await tester.pump();
    expect(find.text('Welcome'), findsOneWidget);
  });
}
Try it yourself: Add a third test: empty email shows the error.
tap Login without typing
HARDReal project: the final steps before the Play StoreExample 10 of 10

Release checklist app

A checklist that tracks your own release steps with a progress bar. Real teams keep exactly this list for every release. Tick items to see the progress.
class Page extends StatefulWidget {
  const Page({super.key});
  @override
  State<Page> createState() => _PageState();
}
class _PageState extends State<Page> {
  final steps = <String, bool>{
    'All tests pass (flutter test)': false,
    'App name and launcher icon set': false,
    'Version increased in pubspec.yaml': false,
    'Keystore created and backed up': false,
    'Release build tested on a real phone': false,
    'Privacy policy URL ready': false,
    'Screenshots and description written': false,
    'App bundle uploaded to Play Console': false,
  };
  @override
  Widget build(BuildContext context) {
    final done = steps.values.where((v) => v).length;
    return Scaffold(
      appBar: AppBar(title: const Text('Release checklist')),
      body: Column(children: [
        Padding(padding: const EdgeInsets.all(12), child: Column(children: [
          Text('$done of ${steps.length} done', style: const TextStyle(fontSize: 18)),
          const SizedBox(height: 6),
          LinearProgressIndicator(value: done / steps.length),
          if (done == steps.length) const Text('Ready to publish!', style: TextStyle(color: Colors.green, fontSize: 20)),
        ])),
        Expanded(child: ListView(children: steps.keys.map((k) => CheckboxListTile(
          title: Text(k), value: steps[k], onChanged: (v) => setState(() => steps[k] = v!),
        )).toList())),
      ]),
    );
  }
}
void main() => runApp(const MaterialApp(home: Page()));
Try it yourself: Add a step: "Crash reporting added".
Add a key to the map.

Quick quiz

3 questions. Click an answer.
Which command runs all your tests?
flutter runflutter testflutter buildflutter doctor
Which widget helps Flutter skip rebuilding something that never changes?
constlatedynamicasync
What must you never lose when publishing an app?
The keystore (signing key)The READMEThe test folderThe .gitignore
Score: 0 / 3

Recap: what you learned in Module 19

Unit tests

test() and expect() check plain Dart code.

Widget tests

pumpWidget, find, tap, pump.

Debugging

debugPrint and DevTools.

Performance

const, small widgets, ListView.builder.

Release

Version, keystore, appbundle.

Publish

Play Console, screenshots, privacy policy.

Next: Capstone Projects and Career - Build real apps, build your portfolio
MODULE 20 · PART 5

Capstone Projects and Career

Build real apps, build your portfolio
You will learn
  • Plan an app from idea to screens
  • Combine widgets, state, lists, forms and APIs
  • Build 10 complete mini-apps for your portfolio
  • Share your work with Git, README and an APK
  • Know the next steps for jobs, freelancing and hackathons
You will build: ten complete mini-apps
8 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
🎓

Where is this used in real apps?

This is where everything comes together. Each project uses many modules at once, just like a real job. Finish them, put them on GitHub and show them to employers and clients.

Portfolio

Three to five finished apps beat any certificate.

Real clients

Business card, billing, attendance and shop apps are what local businesses ask for.

Confidence

After these projects you can build a first version of almost any simple app.

My portfolio
💼
Expense tracker
GitHub
🛒
Grocery store
GitHub
🏆
Attendance app
Play Store

What makes a good project?

A good capstone project has a real user, solves a real problem and uses several skills: layout, state, lists, forms and data. Every example below is a small version of a real business app.

Business card

Layout, Column, Row, Icon.

Calculators

TextField, state, maths.

Notes and flashcards

Lists, setState, CRUD.

Trackers

Forms, lists, totals, categories.

Data apps

HTTP, FutureBuilder, search and filter.

Store and attendance

Provider, tabs, multi-screen.

Tip: after you run an example, change it: new colours, your city, your own data. That makes it yours.

Animated explainer: From idea to Play Store

Press Next to walk through it step by step, or Auto play.

How to plan a project before coding

1. Idea in one line

Who is it for and what problem does it solve? Example: "A fee tracker for coaching centres in Ranchi."

2. Features list

Write must-have (MVP) and nice-to-have. Build only the must-haves first.

3. Draw screens

Pen and paper is enough. 3 to 5 screens. Draw how the user moves between them.

4. Choose tools

State: setState or Provider? Data: local (Hive) or cloud (Firebase)? Pick the simplest that works.

5. Build in small steps

One screen at a time. Run the app after every small change.

6. Test and polish

Try it on a real phone. Ask a friend to use it without help.

Rule of thumb: a small finished app beats a big half-finished one. Employers love finished projects.

Git, README and sharing your work

Git basics

git init
git add .
git commit -m "first screen"
Commit after every working step.

GitHub

Create a free repository, then git remote add origin URL and git push -u origin main. This is your online portfolio.

README.md

App name, 3 screenshots, features list, how to run (flutter pub get, flutter run), tech used, your name and contact.

Share the APK: flutter build apk --release creates build/app/outputs/flutter-apk/app-release.apk. Send it on WhatsApp or upload it to Drive so friends can test.
Add a .gitignore (the Flutter template has one) so the build folder is not uploaded.
EASYReal project: a visiting card for a shop or freelancerExample 1 of 10

Digital business card

Layout only: Column, Row, CircleAvatar, Icon and Text. Local businesses love a card they can share on WhatsApp. Combines Module 5 to 7.
class Page extends StatefulWidget {
  const Page({super.key});
  @override
  State<Page> createState() => _PageState();
}
class _PageState extends State<Page> {

  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('My card')),
    body: Center(child: Card(margin: const EdgeInsets.all(20), child: Padding(padding: const EdgeInsets.all(20), child: Column(mainAxisSize: MainAxisSize.min, children: [
      const CircleAvatar(radius: 44, backgroundColor: Colors.indigo, child: Text('AK', style: TextStyle(fontSize: 30, color: Colors.white))),
      const SizedBox(height: 10),
      const Text('Asha Kumari', style: TextStyle(fontSize: 26, fontWeight: FontWeight.bold)),
      const Text('Flutter Developer, Ranchi'),
      const Divider(height: 24),
      const ListTile(leading: Icon(Icons.call), title: Text('+91 98765 43210')),
      const ListTile(leading: Icon(Icons.email), title: Text('asha@ranchi.in')),
      const ListTile(leading: Icon(Icons.location_on), title: Text('Main Road, Ranchi')),
    ])))),
  );
}
void main() => runApp(const MaterialApp(home: Page()));
Try it yourself: Use your own name and a different avatar colour.
Edit the Text widgets and backgroundColor.
EASYReal project: restaurant or shop billExample 2 of 10

Tip and bill split calculator

TextField, state and simple maths. The result updates live as you type. Combines Modules 4, 9 and 10.
class Page extends StatefulWidget {
  const Page({super.key});
  @override
  State<Page> createState() => _PageState();
}
class _PageState extends State<Page> {
  double bill = 0;
  double tip = 10;
  int people = 2;
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Bill split')),
    body: Padding(padding: const EdgeInsets.all(20), child: Column(children: [
      TextField(keyboardType: TextInputType.number, onChanged: (v) => setState(() => bill = double.tryParse(v) ?? 0), decoration: const InputDecoration(labelText: 'Bill amount (Rs)', border: OutlineInputBorder())),
      const SizedBox(height: 12),
      Text('Tip: ${tip.round()}%', style: const TextStyle(fontSize: 18)),
      Slider(value: tip, min: 0, max: 20, divisions: 20, onChanged: (v) => setState(() => tip = v)),
      Row(children: [const Text('People: '), IconButton(onPressed: () => setState(() { if (people > 1) people--; }), icon: const Icon(Icons.remove)), Text('$people'), IconButton(onPressed: () => setState(() => people++), icon: const Icon(Icons.add))]),
      const Divider(),
      Text('Total: Rs ${(bill * (1 + tip / 100)).toStringAsFixed(2)}', style: const TextStyle(fontSize: 22)),
      Text('Each pays: Rs ${(bill * (1 + tip / 100) / people).toStringAsFixed(2)}', style: const TextStyle(fontSize: 24, color: Colors.green)),
    ])),
  );
}
void main() => runApp(const MaterialApp(home: Page()));
Try it yourself: Add a 5% GST line.
bill * 0.05
EASYReal project: kitchen, shop and school toolsExample 3 of 10

Unit converter

A list of conversions with one input. Uses a Map of factors, a dropdown and a result card. Combines Modules 4, 7 and 9.
class Page extends StatefulWidget {
  const Page({super.key});
  @override
  State<Page> createState() => _PageState();
}
class _PageState extends State<Page> {
  double value = 1;
  String kind = 'km to miles';
  final factors = <String, double>{'km to miles': 0.621371, 'kg to pounds': 2.20462, 'metres to feet': 3.28084, 'litres to gallons': 0.264172};
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Converter')),
    body: Padding(padding: const EdgeInsets.all(20), child: Column(children: [
      TextField(keyboardType: TextInputType.number, onChanged: (v) => setState(() => value = double.tryParse(v) ?? 0), decoration: const InputDecoration(labelText: 'Value', border: OutlineInputBorder())),
      const SizedBox(height: 12),
      DropdownButton<String>(value: kind, isExpanded: true, items: factors.keys.map((k) => DropdownMenuItem(value: k, child: Text(k))).toList(), onChanged: (v) => setState(() => kind = v!)),
      const SizedBox(height: 20),
      Text('${(value * factors[kind]!).toStringAsFixed(3)}', style: const TextStyle(fontSize: 36, color: Colors.indigo)),
    ])),
  );
}
void main() => runApp(const MaterialApp(home: Page()));
Try it yourself: Add "cm to inches" (0.393701).
'cm to inches': 0.393701
EASYReal project: daily to-do and shopping notesExample 4 of 10

Notes app

Add and delete items in a list. This is CRUD, the base of almost every business app. Combines Modules 8, 9 and 10.
class Page extends StatefulWidget {
  const Page({super.key});
  @override
  State<Page> createState() => _PageState();
}
class _PageState extends State<Page> {
  final c = TextEditingController();
  final notes = <String>['Pay electricity bill', 'Call Rohit about order'];
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('My notes')),
    body: Column(children: [
      Padding(padding: const EdgeInsets.all(12), child: Row(children: [
        Expanded(child: TextField(controller: c, decoration: const InputDecoration(hintText: 'Write a note', border: OutlineInputBorder()))),
        IconButton(onPressed: () { if (c.text.trim().isNotEmpty) setState(() { notes.insert(0, c.text.trim()); c.clear(); }); }, icon: const Icon(Icons.add_circle, color: Colors.indigo, size: 36)),
      ])),
      Expanded(child: ListView.builder(itemCount: notes.length, itemBuilder: (context, i) => ListTile(leading: const Icon(Icons.note), title: Text(notes[i]), trailing: IconButton(icon: const Icon(Icons.delete), onPressed: () => setState(() => notes.removeAt(i)))))),
    ]),
  );
}
void main() => runApp(const MaterialApp(home: Page()));
Try it yourself: Show the note count in the title.
Text('My notes (${notes.length})')
EASYReal project: learning words, formulas, GK for examsExample 5 of 10

Flashcards

Tap the card to flip between question and answer, then go to the next card. Uses a list, an index and a conditional. Combines Modules 4 and 9.
class Page extends StatefulWidget {
  const Page({super.key});
  @override
  State<Page> createState() => _PageState();
}
class _PageState extends State<Page> {
  int i = 0;
  bool showA = false;
  final cards = [['Capital of Jharkhand?', 'Ranchi'], ['River of Ranchi (Hundru Falls)?', 'Subarnarekha'], ['Dart: variable that never changes?', 'final / const'], ['Widget for scrolling list?', 'ListView']];
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Flashcards')),
    body: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
      Text('Card ${i + 1} of ${cards.length}'),
      GestureDetector(onTap: () => setState(() => showA = !showA), child: Container(width: 300, height: 180, margin: const EdgeInsets.all(16), alignment: Alignment.center, padding: const EdgeInsets.all(16), decoration: BoxDecoration(color: showA ? Colors.green.shade100 : Colors.indigo.shade100, borderRadius: BorderRadius.circular(18)), child: Text(showA ? cards[i][1] : cards[i][0], textAlign: TextAlign.center, style: const TextStyle(fontSize: 22)))),
      Text(showA ? 'Answer (tap to flip)' : 'Question (tap to flip)'),
      ElevatedButton(onPressed: () => setState(() { i = (i + 1) % cards.length; showA = false; }), child: const Text('Next card')),
    ])),
  );
}
void main() => runApp(const MaterialApp(home: Page()));
Try it yourself: Add two cards of your own.
Add lists to cards.
MEDIUMReal project: personal and small-shop daily expensesExample 6 of 10

Expense tracker

A form, a category filter, a running total and a list. Add an expense with amount and category; the total updates. Combines Modules 8, 9, 10 and 13.
class Expense {
  final String title;
  final int amount;
  final String cat;
  Expense(this.title, this.amount, this.cat);
}
class Page extends StatefulWidget {
  const Page({super.key});
  @override
  State<Page> createState() => _PageState();
}
class _PageState extends State<Page> {
  final list = <Expense>[Expense('Auto fare', 40, 'Travel'), Expense('Samosa', 20, 'Food')];
  final t = TextEditingController();
  final a = TextEditingController();
  String cat = 'Food';
  String filter = 'All';
  @override
  Widget build(BuildContext context) {
    final shown = list.where((e) => filter == 'All' || e.cat == filter).toList();
    final total = shown.fold(0, (s, e) => s + e.amount);
    return Scaffold(
      appBar: AppBar(title: Text('Total: Rs $total')),
      body: Column(children: [
        Padding(padding: const EdgeInsets.all(8), child: Row(children: [
          Expanded(child: TextField(controller: t, decoration: const InputDecoration(hintText: 'What'))),
          const SizedBox(width: 8),
          SizedBox(width: 70, child: TextField(controller: a, keyboardType: TextInputType.number, decoration: const InputDecoration(hintText: 'Rs'))),
          IconButton(icon: const Icon(Icons.add_circle), onPressed: () {
            final v = int.tryParse(a.text);
            if (v != null && t.text.isNotEmpty) setState(() { list.insert(0, Expense(t.text, v, cat)); t.clear(); a.clear(); });
          }),
        ])),
        Wrap(spacing: 6, children: ['All', 'Food', 'Travel', 'Study'].map((c) => ChoiceChip(label: Text(c), selected: filter == c, onSelected: (_) => setState(() { filter = c; if (c != 'All') cat = c; }))).toList()),
        Expanded(child: ListView(children: shown.map((e) => ListTile(leading: const Icon(Icons.currency_rupee), title: Text(e.title), subtitle: Text(e.cat), trailing: Text('Rs ${e.amount}'))).toList())),
      ]),
    );
  }
}
void main() => runApp(const MaterialApp(home: Page()));
Try it yourself: Add a "Study" expense using the chips.
Tap Study, then add.
MEDIUMReal project: a city weather appExample 7 of 10

Weather dashboard

HTTP call with loading, data and error states using FutureBuilder. Change the city to see a 404 error handled. API is a stand-in (simulated). Combines Module 14.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class Page extends StatefulWidget {
  const Page({super.key});
  @override
  State<Page> createState() => _PageState();
}
class _PageState extends State<Page> {
  String city = 'ranchi';
  late Future<Map<String, dynamic>> f = load();
  Future<Map<String, dynamic>> load() async {
    final r = await http.get(Uri.parse('https://api.brainbit-teaching.com/weather?q=$city'));
    if (r.statusCode != 200) throw Exception('City not found');
    return jsonDecode(r.body);
  }
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Weather')),
    body: Column(children: [
      Wrap(spacing: 8, children: ['ranchi', 'patna', 'dhanbad', 'delhi'].map((c) => ChoiceChip(label: Text(c), selected: city == c, onSelected: (_) => setState(() { city = c; f = load(); }))).toList()),
      Expanded(child: FutureBuilder<Map<String, dynamic>>(future: f, builder: (context, s) {
        if (s.connectionState != ConnectionState.done) return const Center(child: CircularProgressIndicator());
        if (s.hasError) return Center(child: Text('${s.error}', style: const TextStyle(color: Colors.red)));
        final w = s.data!;
        return Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
          Text(w['city'], style: const TextStyle(fontSize: 28)),
          Text('${w['temp'].toStringAsFixed(1)} C', style: const TextStyle(fontSize: 56)),
          Text(w['desc']),
          Text('Humidity ${w['humidity']}%'),
        ]));
      })),
    ]),
  );
}
void main() => runApp(const MaterialApp(home: Page()));
Try it yourself: Add Bokaro as a chip (it will show the error state).
Add 'bokaro' to the list.
MEDIUMReal project: an institute app listing coursesExample 8 of 10

Course catalogue with search

Search box plus filter chips over a grid of cards. Searching and filtering use the same list with where. Combines Modules 8, 9 and 10.
class Page extends StatefulWidget {
  const Page({super.key});
  @override
  State<Page> createState() => _PageState();
}
class _PageState extends State<Page> {
  final courses = [
    ['Flutter', 'Mobile', 'Rs 12,000'], ['Python', 'Programming', 'Rs 9,000'], ['Java', 'Programming', 'Rs 10,000'],
    ['React', 'Web', 'Rs 11,000'], ['HTML and CSS', 'Web', 'Rs 5,000'], ['Excel', 'Office', 'Rs 3,500'],
  ];
  String q = '';
  String cat = 'All';
  @override
  Widget build(BuildContext context) {
    final shown = courses.where((c) => (cat == 'All' || c[1] == cat) && c[0].toLowerCase().contains(q.toLowerCase())).toList();
    return Scaffold(
      appBar: AppBar(title: Text('Courses (${shown.length})')),
      body: Column(children: [
        Padding(padding: const EdgeInsets.all(8), child: TextField(onChanged: (v) => setState(() => q = v), decoration: const InputDecoration(prefixIcon: Icon(Icons.search), hintText: 'Search course', border: OutlineInputBorder()))),
        Wrap(spacing: 6, children: ['All', 'Mobile', 'Web', 'Programming', 'Office'].map((c) => ChoiceChip(label: Text(c), selected: cat == c, onSelected: (_) => setState(() => cat = c))).toList()),
        Expanded(child: GridView.count(crossAxisCount: 2, padding: const EdgeInsets.all(8), mainAxisSpacing: 8, crossAxisSpacing: 8, children: shown.map((c) => Card(child: Padding(padding: const EdgeInsets.all(10), child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
          const Icon(Icons.school, size: 36, color: Colors.indigo),
          Text(c[0], style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
          Text(c[1]),
          Text(c[2], style: const TextStyle(color: Colors.green)),
        ])))).toList())),
      ]),
    );
  }
}
void main() => runApp(const MaterialApp(home: Page()));
Try it yourself: Add a "Tally" course in the Office category.
['Tally', 'Office', 'Rs 4,000']
HARDReal project: school or coaching class attendanceExample 9 of 10

Attendance app with tabs

Two tabs share one list: mark present or absent, then see the summary with percentage. This is the shape of a real attendance product. Combines Modules 8, 9 and 11.
class Page extends StatefulWidget {
  const Page({super.key});
  @override
  State<Page> createState() => _PageState();
}
class _PageState extends State<Page> {
  final present = <String, bool>{'Asha Kumari': true, 'Rohit Singh': true, 'Pooja Sahu': false, 'Vikash Oraon': true, 'Sunita Devi': false, 'Amit Mahto': true};
  @override
  Widget build(BuildContext context) {
    final p = present.values.where((v) => v).length;
    final pct = p / present.length;
    return DefaultTabController(length: 2, child: Scaffold(
      appBar: AppBar(title: const Text('Class 10-A'), bottom: const TabBar(tabs: [Tab(text: 'Mark'), Tab(text: 'Summary')])),
      body: TabBarView(children: [
        ListView(children: present.keys.map((n) => SwitchListTile(title: Text(n), subtitle: Text(present[n]! ? 'Present' : 'Absent'), value: present[n]!, onChanged: (v) => setState(() => present[n] = v))).toList()),
        Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
          Text('${(pct * 100).round()}%', style: const TextStyle(fontSize: 64, color: Colors.indigo)),
          Text('$p present, ${present.length - p} absent'),
          const SizedBox(height: 12),
          SizedBox(width: 240, child: LinearProgressIndicator(value: pct, minHeight: 12)),
        ])),
      ]),
    ));
  }
}
void main() => runApp(const MaterialApp(home: Page()));
Try it yourself: Add two more students.
Add entries to the present map.
HARDReal project: a local kirana store ordering appExample 10 of 10

Grocery store with cart

Product list, cart with quantity and total, checkout in a bottom sheet. Uses Provider so the list and the cart share data. Combines Modules 8, 11, 13. This is the final project: extend it with Firebase or an API.
import 'package:provider/provider.dart';

class Cart extends ChangeNotifier {
  final qty = <String, int>{};
  void add(String n) { qty[n] = (qty[n] ?? 0) + 1; notifyListeners(); }
  void remove(String n) { if ((qty[n] ?? 0) > 0) { qty[n] = qty[n]! - 1; notifyListeners(); } }
  int get count => qty.values.fold(0, (a, b) => a + b);
}
const prices = <String, int>{'Rice 5kg': 320, 'Atta 5kg': 240, 'Dal 1kg': 130, 'Mustard oil 1L': 180, 'Tea 250g': 95};

class Shop extends StatelessWidget {
  const Shop({super.key});
  @override
  Widget build(BuildContext context) {
    final cart = context.watch<Cart>();
    final total = prices.entries.fold(0, (s, e) => s + e.value * (cart.qty[e.key] ?? 0));
    return Scaffold(
      appBar: AppBar(title: const Text('Ranchi Kirana'), actions: [Center(child: Padding(padding: const EdgeInsets.all(12), child: Text('Cart ${cart.count}')))]),
      body: ListView(children: prices.entries.map((e) => ListTile(
        title: Text(e.key), subtitle: Text('Rs ${e.value}'),
        trailing: Row(mainAxisSize: MainAxisSize.min, children: [
          IconButton(icon: const Icon(Icons.remove_circle_outline), onPressed: () => cart.remove(e.key)),
          Text('${cart.qty[e.key] ?? 0}'),
          IconButton(icon: const Icon(Icons.add_circle, color: Colors.green), onPressed: () => cart.add(e.key)),
        ]),
      )).toList()),
      bottomNavigationBar: Padding(padding: const EdgeInsets.all(12), child: ElevatedButton(
        onPressed: total == 0 ? null : () => showModalBottomSheet(context: context, builder: (_) => Padding(padding: const EdgeInsets.all(24), child: Column(mainAxisSize: MainAxisSize.min, children: [
          const Text('Order placed!', style: TextStyle(fontSize: 24)),
          Text('Pay Rs $total on delivery'),
        ]))),
        child: Text('Checkout: Rs $total'),
      )),
    );
  }
}
void main() => runApp(ChangeNotifierProvider(create: (_) => Cart(), child: const MaterialApp(home: Shop())));
Try it yourself: Add "Sugar 1kg" at Rs 48.
Add to the prices map.

Quick quiz

3 questions. Click an answer.
What should you build first?
Every featureThe must-have (MVP) featuresThe logoThe settings page
Which file explains your project on GitHub?
README.mdpubspec.yamlmain.dart.gitignore
What command creates an APK to share with friends?
flutter runflutter build apk --releaseflutter cleangit push
Score: 0 / 3

Recap: what you learned in Module 20

Plan first

Idea, features, screens, tools.

Combine skills

Layout, state, lists, forms, API, Provider.

Ten projects

From business card to grocery store.

Share

Git, README, APK.

Career

Local jobs, remote work, internships, hackathons.

Keep building

Finish three apps and publish one.

Next: the next part of the course.

Career roadmap: what next?

Jobs in and near Ranchi

Junior Flutter developer, mobile app developer, freelance app builder for local shops, schools and coaching centres. Companies in Ranchi, Jamshedpur, Patna, Kolkata, Bengaluru and Hyderabad hire freshers with a good portfolio.

Remote and freelance

Upwork, Freelancer, LinkedIn and Internshala. Start with small gigs (Rs 5,000 to 20,000), collect reviews, then raise your rate.

Internships and hackathons

Internshala, LinkedIn, college placement cell, state startup hackathons and Smart India Hackathon. A hackathon app is a great portfolio piece.

Skills to add next

Clean architecture, Riverpod or BLoC, REST and Firebase, CI/CD, unit and widget tests, Play Store publishing.

Portfolio

3 finished apps on GitHub with README and screenshots, 1 app on Play Store, a LinkedIn post for each.

Interview prep

Dart basics, widget lifecycle, state management, async/await, JSON, and one app you can explain end to end.

Click the name to edit it, then press Ctrl+P to print or save as PDF.
BRAINBIT INFOTECH, RANCHI
Certificate of Completion
This is to certify that
Your Name Here
has successfully completed the
Flutter App Development Course
20 modules, 200 practical examples, 10 capstone apps
Date
🏆
Nandan Kumar, Trainer

Code Lab - write any Dart / Flutter code (Ctrl+Enter to run)