COMPLETE FLUTTER COURSE · BRAINBIT INFOTECH

Part 4

4 modules · 16 class hours · 40 practical examples

Module 13: Provider: Share State Across Screens

One source of truth for the whole app · 4 h

Module 14: JSON, HTTP and REST APIs

Get live data from the internet · 4 h

Module 15: Local Storage: SharedPreferences, SQLite, Hive

Keep data even after the app closes · 4 h

Module 16: Firebase: Login and Cloud Database

Real login and online data without writing a server · 4 h

MODULE 13 · PART 4

Provider: Share State Across Screens

One source of truth for the whole app
You will learn
  • See why setState is not enough for big apps
  • Create a ChangeNotifier model
  • Provide it with ChangeNotifierProvider
  • Read it with watch, read and Consumer
  • Build cart, favourites and expense tracker apps
You will build: a shopping cart and an expense tracker
4 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
🔄

Where is this used in real apps?

The cart count in the AppBar, the cart page and the product page must all show the same data. Provider keeps one shared copy.

Shared data

Cart, logged-in user, theme, favourites: needed on many screens.

Model class

All the logic lives in one ChangeNotifier class, not inside widgets.

Auto update

Call notifyListeners() and every widget that watches it rebuilds.

Cart (3)
🛒
Items in cart
3
💰
Total
Rs 1,245
✅
Same value on every screen
Provider

The problem with setState

setState works for one widget. But if the product page adds an item and the AppBar on another page must show the new count, how does the data travel?

Passing down

Pass data through many constructors. Long and painful ("prop drilling").

Lifting up

Keep data in a parent far above. Hard to manage.

Provider

Put data in ONE model. Any widget anywhere can read it and rebuild when it changes.

Provider is the most common starter solution and is recommended in the Flutter docs. Riverpod and Bloc are bigger cousins.

Step 1: write a model

A ChangeNotifier is a normal Dart class that can call notifyListeners(). Put your data and your logic (add, remove, total) here. No widgets inside!

Rule: every method that changes data must end with notifyListeners().
import 'package:provider/provider.dart';

class CartModel extends ChangeNotifier {
  final List<String> _items = [];

  List<String> get items => List.unmodifiable(_items);
  int get count => _items.length;

  void add(String item) {
    _items.add(item);
    notifyListeners();        // tell every listener: data changed
  }

  void clear() {
    _items.clear();
    notifyListeners();
  }
}

Step 2: provide it

ChangeNotifierProvider creates the model once and makes it available to all widgets below it. Put it above MaterialApp so every screen can reach it.

MultiProvider avoids nesting when you have more than one model.
import 'package:provider/provider.dart';

void main() {
  runApp(
    ChangeNotifierProvider(
      create: (context) => CartModel(),
      child: const MyApp(),
    ),
  );
}

// several models at once
MultiProvider(
  providers: [
    ChangeNotifierProvider(create: (_) => CartModel()),
    ChangeNotifierProvider(create: (_) => ThemeModel()),
  ],
  child: const MyApp(),
)

Step 3: watch, read, Consumer

watch = "show this data and redraw when it changes". read = "just do something". Consumer = watch for a small part of the tree.

Big mistake to avoid: never use watch inside onPressed. Use read there.
import 'package:provider/provider.dart';

// rebuilds this widget when the model changes
final cart = context.watch<CartModel>();
Text('Items: ${cart.count}')

// just calls a method, never rebuilds (use in onPressed)
ElevatedButton(
  onPressed: () => context.read<CartModel>().add('Atta'),
  child: const Text('Add'),
)

// rebuilds only a small part
Consumer<CartModel>(
  builder: (context, cart, child) => Text('${cart.count}'),
)

watch vs read: simple rule

Inside build() and showing data

context.watch or Consumer.

Inside onPressed, onTap, initState

context.read.

Only one field needed

context.select((CartModel c) => c.count) rebuilds only when that field changes.

Where to keep logic

In the model. Widgets only show data and call methods.

Memory trick: watch = eyes (show), read = hands (do).

Animated explainer: How Provider updates the screen

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

Animated explainer: Widgets show, models decide

Press Next to walk through it step by step, or Auto play.
EASYReal project: any shared number: cart count, scoreExample 1 of 10

ChangeNotifier counter

The simplest Provider app. The number lives in a model; the button calls read().inc(); the text watches it.
import 'package:provider/provider.dart';

class Counter extends ChangeNotifier {
  int count = 0;
  void inc() { count++; notifyListeners(); }
}

void main() => runApp(ChangeNotifierProvider(
  create: (_) => Counter(),
  child: MaterialApp(home: Builder(builder: (context) => Scaffold(
    body: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
      Text('${context.watch<Counter>().count}', style: const TextStyle(fontSize: 60)),
      ElevatedButton(onPressed: () => context.read<Counter>().inc(), child: const Text('Add')),
    ])),
  ))),
));
Try it yourself: Add a decrement method and a button for it.
void dec() { count--; notifyListeners(); }
EASYReal project: rebuild only one small partExample 2 of 10

Consumer widget

Consumer wraps only the part that needs the data. Here just the Text rebuilds, not the whole screen.
import 'package:provider/provider.dart';

class Counter extends ChangeNotifier {
  int count = 0;
  void inc() { count++; notifyListeners(); }
}

void main() => runApp(ChangeNotifierProvider(
  create: (_) => Counter(),
  child: MaterialApp(home: Builder(builder: (context) => Scaffold(
    body: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
      const Text('Visitors today'),
      Consumer<Counter>(builder: (context, c, child) => Text('${c.count}', style: const TextStyle(fontSize: 60))),
      Builder(builder: (context) => ElevatedButton(onPressed: () => context.read<Counter>().inc(), child: const Text('New visitor'))),
    ])),
  ))),
));
Try it yourself: Show "Busy!" when count is above 5.
Use c.count > 5 ? 'Busy!' : ...
EASYReal project: avoid common mistakesExample 3 of 10

watch vs read

watch in build to show data, read in button handlers. The second text uses select so it only rebuilds when the even/odd answer changes.
import 'package:provider/provider.dart';

class Counter extends ChangeNotifier {
  int count = 0;
  void inc() { count++; notifyListeners(); }
}

void main() => runApp(ChangeNotifierProvider(
  create: (_) => Counter(),
  child: MaterialApp(home: Builder(builder: (context) => Scaffold(
    body: Builder(builder: (context) {
      final n = context.watch<Counter>().count;
      return Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
        Text('Count: $n', style: const TextStyle(fontSize: 34)),
        Text(n % 2 == 0 ? 'Even' : 'Odd'),
        ElevatedButton(onPressed: () => context.read<Counter>().inc(), child: const Text('Next')),
      ]));
    }),
  ))),
));
Try it yourself: Show "Fizz" when n is divisible by 3.
if (n % 3 == 0) const Text('Fizz')
EASYReal project: dark mode that every screen sharesExample 4 of 10

Theme provider

A ThemeModel holds the mode. The MaterialApp watches it, so one switch anywhere changes the whole app.
import 'package:provider/provider.dart';

class ThemeModel extends ChangeNotifier {
  bool dark = false;
  void toggle() { dark = !dark; notifyListeners(); }
}

void main() => runApp(ChangeNotifierProvider(create: (_) => ThemeModel(), child: const Root()));

class Root extends StatelessWidget {
  const Root({super.key});
  @override
  Widget build(BuildContext context) {
    final t = context.watch<ThemeModel>();
    return MaterialApp(
      theme: ThemeData(colorSchemeSeed: Colors.teal),
      darkTheme: ThemeData(colorSchemeSeed: Colors.teal, brightness: Brightness.dark),
      themeMode: t.dark ? ThemeMode.dark : ThemeMode.light,
      home: Scaffold(
        appBar: AppBar(title: const Text('Settings')),
        body: SwitchListTile(title: const Text('Dark mode'), value: t.dark, onChanged: (_) => context.read<ThemeModel>().toggle()),
      ),
    );
  }
}
Try it yourself: Add a second text "Mode: Dark / Light" under the switch.
Text(t.dark ? 'Mode: Dark' : 'Mode: Light')
EASYReal project: wishlist / bookmarksExample 5 of 10

Favourites list

The model keeps a Set of favourite names. Tapping a heart adds or removes it, and a header counts the total.
import 'package:provider/provider.dart';

class Favs extends ChangeNotifier {
  final Set<String> items = {};
  bool has(String n) => items.contains(n);
  void toggle(String n) { has(n) ? items.remove(n) : items.add(n); notifyListeners(); }
}

void main() => runApp(ChangeNotifierProvider(
  create: (_) => Favs(),
  child: MaterialApp(home: Builder(builder: (context) => Scaffold(
    appBar: AppBar(title: Text('Favourites: ${context.watch<Favs>().items.length}')),
    body: ListView(children: ['Hundru Falls', 'Rock Garden', 'Tagore Hill', 'Jagannath Temple'].map((n) => ListTile(
      title: Text(n),
      trailing: IconButton(
        icon: Icon(context.watch<Favs>().has(n) ? Icons.favorite : Icons.favorite_border, color: Colors.red),
        onPressed: () => context.read<Favs>().toggle(n)),
    )).toList()),
  ))),
));
Try it yourself: Add "Dassam Falls".
Add the name to the list.
MEDIUMReal project: e-commerce cartExample 6 of 10

Cart model with total

The model keeps a list of CartItem objects and computes the total with a getter. Any screen can show it.
import 'package:provider/provider.dart';

class Item { final String name; final int price; Item(this.name, this.price); }
class Cart extends ChangeNotifier {
  final List<Item> items = [];
  int get total => items.fold(0, (s, i) => s + i.price);
  void add(Item i) { items.add(i); notifyListeners(); }
  void removeAt(int k) { items.removeAt(k); notifyListeners(); }
}

void main() => runApp(ChangeNotifierProvider(
  create: (_) => Cart(),
  child: MaterialApp(home: Builder(builder: (context) => Scaffold(
    appBar: AppBar(title: Text('Cart: ${context.watch<Cart>().items.length}  Rs ${context.watch<Cart>().total}')),
    body: Column(children: [
      Wrap(spacing: 8, children: [Item('Atta', 245), Item('Rice', 380), Item('Dal', 140)].map((i) =>
        ActionChip(label: Text('+ ${i.name}'), onPressed: () => context.read<Cart>().add(i))).toList()),
      Expanded(child: ListView.builder(itemCount: context.watch<Cart>().items.length, itemBuilder: (c, k) {
        final it = context.watch<Cart>().items[k];
        return ListTile(title: Text(it.name), trailing: Text('Rs ${it.price}'), onTap: () => context.read<Cart>().removeAt(k));
      })),
    ]),
  ))),
));
Try it yourself: Add "Sugar" at Rs 48.
Item('Sugar', 48) in the list of chips.
MEDIUMReal project: todo list shared by two screensExample 7 of 10

Todo model

The model owns the list and has add, toggle and remove. A getter counts done tasks. UI code stays tiny.
import 'package:provider/provider.dart';

class Task { String title; bool done; Task(this.title, [this.done = false]); }
class Todos extends ChangeNotifier {
  final List<Task> tasks = [Task('Revise Dart'), Task('Practice Provider')];
  int get done => tasks.where((t) => t.done).length;
  void add(String t) { tasks.add(Task(t)); notifyListeners(); }
  void toggle(Task t) { t.done = !t.done; notifyListeners(); }
  void remove(Task t) { tasks.remove(t); notifyListeners(); }
}

void main() => runApp(ChangeNotifierProvider(
  create: (_) => Todos(),
  child: MaterialApp(home: Builder(builder: (context) => Scaffold(
    appBar: AppBar(title: Text('Done ${context.watch<Todos>().done}/${context.watch<Todos>().tasks.length}')),
    body: ListView(children: context.watch<Todos>().tasks.map((t) => CheckboxListTile(
      title: Text(t.title, style: TextStyle(decoration: t.done ? TextDecoration.lineThrough : null)),
      value: t.done, onChanged: (_) => context.read<Todos>().toggle(t),
      secondary: IconButton(icon: const Icon(Icons.delete), onPressed: () => context.read<Todos>().remove(t)))).toList()),
    floatingActionButton: FloatingActionButton(onPressed: () => context.read<Todos>().add('New task'), child: const Icon(Icons.add)),
  ))),
));
Try it yourself: Add a third default task.
Add Task('...') to the list.
MEDIUMReal project: cart + theme in one appExample 8 of 10

Two providers together

MultiProvider registers several models at once. Each widget watches only the model it needs.
import 'package:provider/provider.dart';

class Counter extends ChangeNotifier {
  int n = 0;
  void inc() { n++; notifyListeners(); }
}
class Name extends ChangeNotifier {
  String v = 'Guest';
  void set(String x) { v = x; notifyListeners(); }
}

void main() => runApp(MultiProvider(
  providers: [
    ChangeNotifierProvider(create: (_) => Counter()),
    ChangeNotifierProvider(create: (_) => Name()),
  ],
  child: MaterialApp(home: Scaffold(body: Center(child: Builder(builder: (context) => Column(mainAxisSize: MainAxisSize.min, children: [
    Text('Hello, ${context.watch<Name>().v}', style: const TextStyle(fontSize: 28)),
    Text('Clicks: ${context.watch<Counter>().n}'),
    ElevatedButton(onPressed: () => context.read<Counter>().inc(), child: const Text('Click')),
    ElevatedButton(onPressed: () => context.read<Name>().set('Asha'), child: const Text('Login as Asha')),
  ]))))),
));
Try it yourself: Add a "Logout" button that sets the name back to Guest.
context.read().set('Guest')
HARDReal project: full e-commerce flowExample 9 of 10

Shopping cart with badge

Three parts share one Cart model: a product grid with Add buttons, an AppBar badge showing the count, and a cart dialog with the total. Exactly how a real store works.
import 'package:provider/provider.dart';

class Cart extends ChangeNotifier {
  final Map<String, int> qty = {};
  final prices = {'School Bag': 649, 'Bottle': 199, 'Notebooks': 120, 'Lunch Box': 249};
  int get count => qty.values.fold(0, (a, b) => a + b);
  int get total => qty.entries.fold(0, (s, e) => s + prices[e.key]! * e.value);
  void add(String n) { qty[n] = (qty[n] ?? 0) + 1; notifyListeners(); }
  void less(String n) { if ((qty[n] ?? 0) > 1) { qty[n] = qty[n]! - 1; } else { qty.remove(n); } notifyListeners(); }
}

void main() => runApp(ChangeNotifierProvider(
  create: (_) => Cart(),
  child: MaterialApp(home: Builder(builder: (context) => Scaffold(
    appBar: AppBar(title: const Text('Ranchi Mart'), actions: [
      Builder(builder: (context) => IconButton(
        icon: Badge(label: Text('${context.watch<Cart>().count}'), child: const Icon(Icons.shopping_cart)),
        onPressed: () => showDialog(context: context, builder: (_) => AlertDialog(
          title: const Text('Your cart'),
          content: Text(context.read<Cart>().qty.entries.map((e) => '${e.key} x${e.value}').join(', ') + '\nTotal Rs ${context.read<Cart>().total}'))))),
    ]),
    body: Builder(builder: (context) {
      final cart = context.watch<Cart>();
      return ListView(children: cart.prices.entries.map((e) => ListTile(
        title: Text(e.key), subtitle: Text('Rs ${e.value}'),
        trailing: Row(mainAxisSize: MainAxisSize.min, children: [
          if ((cart.qty[e.key] ?? 0) > 0) IconButton(icon: const Icon(Icons.remove_circle_outline), onPressed: () => context.read<Cart>().less(e.key)),
          Text('${cart.qty[e.key] ?? 0}'),
          IconButton(icon: const Icon(Icons.add_circle), onPressed: () => context.read<Cart>().add(e.key)),
        ]))).toList());
    }),
  ))),
));
Try it yourself: Add "Pen Pack": 60 to prices.
Add the pair to the prices map.
HARDReal project: personal finance / budget appExample 10 of 10

Expense tracker

A model with expenses, a total, a category summary and an add method. A budget bar shows how much of Rs 5,000 is used. Business logic is fully in the model.
import 'package:provider/provider.dart';

class Expense { final String title; final String cat; final int amt; Expense(this.title, this.cat, this.amt); }
class Tracker extends ChangeNotifier {
  final int budget = 5000;
  final List<Expense> list = [Expense('Auto fare', 'Travel', 120), Expense('Groceries', 'Food', 850)];
  int get total => list.fold(0, (s, e) => s + e.amt);
  Map<String, int> get byCat { final m = <String, int>{}; for (final e in list) { m[e.cat] = (m[e.cat] ?? 0) + e.amt; } return m; }
  void add(Expense e) { list.add(e); notifyListeners(); }
}

void main() => runApp(ChangeNotifierProvider(
  create: (_) => Tracker(),
  child: MaterialApp(home: Builder(builder: (context) => Scaffold(
    appBar: AppBar(title: const Text('My Expenses')),
    body: Builder(builder: (context) {
      final t = context.watch<Tracker>();
      return Column(children: [
        Padding(padding: const EdgeInsets.all(16), child: Column(children: [
          Text('Spent Rs ${t.total} of Rs ${t.budget}', style: const TextStyle(fontSize: 18)),
          const SizedBox(height: 8),
          LinearProgressIndicator(value: (t.total / t.budget).clamp(0.0, 1.0), minHeight: 12, color: t.total > t.budget ? Colors.red : Colors.green),
          Wrap(spacing: 6, children: t.byCat.entries.map((e) => Chip(label: Text('${e.key}: ${e.value}'))).toList()),
        ])),
        Expanded(child: ListView(children: t.list.map((e) => ListTile(title: Text(e.title), subtitle: Text(e.cat), trailing: Text('Rs ${e.amt}'))).toList())),
      ]);
    }),
    floatingActionButton: Builder(builder: (context) => FloatingActionButton(
      onPressed: () => context.read<Tracker>().add(Expense('Mobile recharge', 'Bills', 299)), child: const Icon(Icons.add))),
  ))),
));
Try it yourself: Change the budget to 1000. What colour is the bar?
final int budget = 1000; it turns red when total goes above it.

Quick quiz

3 questions. Click an answer.
What must a model method call after changing data?
setStatenotifyListenersrunAppdispose
Which call should you use inside an onPressed?
context.watchcontext.readConsumer onlybuild
Where do you put ChangeNotifierProvider?
Below every widgetAbove the widgets that need the modelIn pubspec.yamlInside a Text
Score: 0 / 3

Recap: what you learned in Module 13

Why

Many screens need the same data.

Model

ChangeNotifier + notifyListeners().

Provide

ChangeNotifierProvider / MultiProvider above the app.

watch

Show data and rebuild.

read

Call methods in handlers.

Logic

Keep rules in the model, UI stays simple.

Next: JSON, HTTP and REST APIs - Get live data from the internet
MODULE 14 · PART 4

JSON, HTTP and REST APIs

Get live data from the internet
You will learn
  • Understand JSON: the language of APIs
  • Convert JSON to Dart objects with fromJson
  • Call APIs with http.get and http.post
  • Show loading, data and error states with FutureBuilder
  • Build users, weather and search screens from an API
You will build: a weather dashboard and a news feed
4 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
🌐

Where is this used in real apps?

Weather, news, bus timings, product lists, bank balance: almost all real data comes from a server through an API, in JSON format.

API

A server address that gives data when you ask. Like a waiter bringing food from the kitchen.

JSON

Plain text with names and values: {"city": "Ranchi", "temp": 27.5}.

States

Every call has 3 states: loading, success, error. Good apps show all three.

Weather
☀
Ranchi
27.5 C, clear sky
🌧
Dhanbad
29 C, light rain
🌫
Patna
31 C, haze

What is an API?

An API (Application Programming Interface) is a web address that returns data instead of a web page. Your app sends a request and the server sends back a response.

GET

Read data: list of users, today weather.

POST

Send new data: register, place an order.

PUT / PATCH

Update existing data.

DELETE

Remove data.

Status codes

200 OK, 201 created, 400 bad request, 401 not logged in, 404 not found, 500 server error.

These slides use a simulated server (no internet needed). The code is the same as with a real API: only the URL changes.

JSON in 2 minutes

JSON has objects { } with named values, lists [ ], text, numbers, true/false and null. jsonDecode turns text into Map and List. jsonEncode does the reverse.

Tip: JSON keys are always in double quotes. Single quotes are not valid JSON.
import 'dart:convert';
import 'package:flutter/material.dart';

// JSON is text. This is an object:
const text = '{"name": "Asha", "age": 21, "city": "Ranchi"}';

// decode: text -> Dart Map
final Map<String, dynamic> m = jsonDecode(text);
print(m['name']);          // Asha

// a list of objects
final list = jsonDecode('[{"id":1},{"id":2}]') as List;
print(list.length);        // 2

// encode: Dart -> text (to send to a server)
print(jsonEncode({'name': 'Rohit', 'marks': [80, 90]}));

Model class with fromJson

Maps are error-prone: a typo in m['nmae'] gives null. A model class gives names, types and auto-complete. fromJson builds it from a Map.

Real use: every API screen has a model: User, Product, Order, Weather.
import 'dart:convert';
import 'package:flutter/material.dart';

class User {
  final int id;
  final String name;
  final String city;
  User({required this.id, required this.name, required this.city});

  factory User.fromJson(Map<String, dynamic> j) =>
      User(id: j['id'], name: j['name'], city: j['city']);

  Map<String, dynamic> toJson() => {'id': id, 'name': name, 'city': city};
}

final u = User.fromJson(jsonDecode(text));
print(u.name);

http.get and async/await

await pauses this function until the answer arrives, without freezing the app. Always check statusCode. Add http: ^1.2.0 to pubspec.yaml first.

Android: add <uses-permission android:name="android.permission.INTERNET"/> in AndroidManifest.xml for release builds.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

Future<List<User>> fetchUsers() async {
  final res = await http.get(Uri.parse('https://api.brainbit-teaching.com/users'));

  if (res.statusCode != 200) {
    throw Exception('Server said ${res.statusCode}');
  }
  final data = jsonDecode(res.body) as List;
  return data.map((j) => User.fromJson(j)).toList();
}

FutureBuilder: loading, data, error

FutureBuilder shows a widget for each stage of a Future. Create the future once (in initState), never inside build(), or it calls the server on every redraw.

Rule: never leave the user with a blank screen. Show a spinner while loading and a message on error.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

FutureBuilder<List<User>>(
  future: future,                       // created once in initState
  builder: (context, snap) {
    if (snap.connectionState != ConnectionState.done) {
      return const Center(child: CircularProgressIndicator());   // loading
    }
    if (snap.hasError) {
      return Center(child: Text('Error: ${snap.error}'));        // error
    }
    final users = snap.data!;                                    // success
    return ListView(children: users.map((u) => ListTile(title: Text(u.name))).toList());
  },
)

Animated explainer: Request and response

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

Animated explainer: Three states of a call

Press Next to walk through it step by step, or Auto play.
EASYReal project: reading any API answerExample 1 of 10

jsonDecode a text

jsonDecode turns JSON text into a Dart Map. Fields are read with square brackets. Run it and look at the console.
import 'dart:convert';
import 'package:flutter/material.dart';

void main() {
  const text = '{"name": "Asha Kumari", "age": 21, "city": "Ranchi", "skills": ["Dart", "Flutter"]}';
  final Map<String, dynamic> m = jsonDecode(text);
  print('Name: ${m['name']}');
  print('City: ${m['city']}');
  print('First skill: ${m['skills'][0]}');
  print('Skills count: ${m['skills'].length}');
  m['age'] = m['age'] + 1;
  print(jsonEncode(m));
}
Try it yourself: Print the age plus 10.
print(m['age'] + 10);
EASYReal project: User / Product / Order classesExample 2 of 10

fromJson model

A model class turns a Map into a typed object. The factory fromJson is the standard way to do it.
import 'dart:convert';
import 'package:flutter/material.dart';

class Student {
  final String name; final String city; final int marks;
  Student({required this.name, required this.city, required this.marks});
  factory Student.fromJson(Map<String, dynamic> j) =>
      Student(name: j['name'], city: j['city'], marks: j['marks']);
  String get grade => marks >= 75 ? 'A' : marks >= 50 ? 'B' : 'C';
}

void main() {
  const text = '[{"name":"Asha","city":"Ranchi","marks":82},{"name":"Rohit","city":"Dhanbad","marks":61},{"name":"Pooja","city":"Bokaro","marks":45}]';
  final list = (jsonDecode(text) as List).map((j) => Student.fromJson(j)).toList();
  for (final s in list) { print('${s.name} (${s.city}): ${s.marks} -> ${s.grade}'); }
}
Try it yourself: Print only students from Ranchi.
list.where((s) => s.city == 'Ranchi')
EASYReal project: first API callExample 3 of 10

http.get in the console

http.get returns a Response with statusCode and body. This calls the simulated server so it works offline.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

Future<void> main() async {
  final res = await http.get(Uri.parse('https://api.brainbit-teaching.com/users'));
  print('Status: ${res.statusCode}');
  final users = jsonDecode(res.body) as List;
  print('Got ${users.length} users');
  for (final u in users) { print('- ${u['name']} from ${u['city']}'); }
}
Try it yourself: Call /users/2 and print only that name.
Uri.parse('.../users/2') and jsonDecode(res.body)['name']
EASYReal project: any screen that loads dataExample 4 of 10

FutureBuilder basics

FutureBuilder shows a spinner first, then the result. The future is created once in initState.
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> {
  late Future<String> f;
  @override
  void initState() { super.initState(); f = load(); }
  Future<String> load() async {
    final r = await http.get(Uri.parse('https://api.brainbit-teaching.com/users/1'));
    return jsonDecode(r.body)['name'];
  }
  @override
  Widget build(BuildContext context) => Scaffold(body: Center(child: FutureBuilder<String>(
    future: f,
    builder: (c, snap) => snap.connectionState != ConnectionState.done
        ? const CircularProgressIndicator()
        : Text('Hello, ${snap.data}', style: const TextStyle(fontSize: 28)),
  )));
}
void main() => runApp(const MaterialApp(home: Page()));
Try it yourself: Show the city as well.
return r.body-based map: jsonDecode(r.body)['city']
EASYReal project: offline or server downExample 5 of 10

Handling errors

Real networks fail. try/catch plus a status check lets the app show a friendly message. The URL with "fail" makes the simulated server answer 500.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

Future<void> call(String url) async {
  try {
    final res = await http.get(Uri.parse(url));
    if (res.statusCode == 200) {
      print('OK: ${res.body.length} characters');
    } else {
      print('Server problem: ${res.statusCode}');
    }
  } catch (e) {
    print('No connection: $e');
  }
}

Future<void> main() async {
  await call('https://api.brainbit-teaching.com/users');
  await call('https://api.brainbit-teaching.com/fail');
  await call('https://api.brainbit-teaching.com/offline');
}
Try it yourself: Add a 4th call to /posts.
await call('.../posts');
MEDIUMReal project: students, customers, employees listExample 6 of 10

Users list from API

The classic API screen: spinner, then a ListView of ListTiles built from the models, with an error state and a Retry button.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class User {
  final String name, city, email;
  User(this.name, this.city, this.email);
  factory User.fromJson(Map<String, dynamic> j) => User(j['name'], j['city'], j['email']);
}
class Users extends StatefulWidget {
  const Users({super.key});
  @override
  State<Users> createState() => _UsersState();
}
class _UsersState extends State<Users> {
  late Future<List<User>> f;
  Future<List<User>> load() async {
    final r = await http.get(Uri.parse('https://api.brainbit-teaching.com/users'));
    if (r.statusCode != 200) throw Exception('Server error ${r.statusCode}');
    return (jsonDecode(r.body) as List).map((j) => User.fromJson(j)).toList();
  }
  @override
  void initState() { super.initState(); f = load(); }
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Users')),
    body: FutureBuilder<List<User>>(future: f, builder: (c, s) {
      if (s.connectionState != ConnectionState.done) return const Center(child: CircularProgressIndicator());
      if (s.hasError) return Center(child: Column(mainAxisSize: MainAxisSize.min, children: [Text('${s.error}'), ElevatedButton(onPressed: () => setState(() => f = load()), child: const Text('Retry'))]));
      return ListView(children: s.data!.map((u) => ListTile(leading: CircleAvatar(child: Text(u.name[0])), title: Text(u.name), subtitle: Text('${u.city} - ${u.email}'))).toList());
    }),
  );
}
void main() => runApp(const MaterialApp(home: Users()));
Try it yourself: Show only users from Ranchi or Dhanbad.
s.data!.where((u) => u.city == 'Ranchi' || u.city == 'Dhanbad')
MEDIUMReal project: register, feedback, place orderExample 7 of 10

POST: send data

http.post sends JSON in the body with a Content-Type header. The server answers 201 with the saved object and its new id.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

Future<void> main() async {
  final body = jsonEncode({'title': 'My first post', 'body': 'Hello from Ranchi', 'userId': 1});
  final res = await http.post(
    Uri.parse('https://api.brainbit-teaching.com/posts'),
    headers: {'Content-Type': 'application/json'},
    body: body,
  );
  print('Status: ${res.statusCode}');
  final saved = jsonDecode(res.body);
  print('Saved with id ${saved['id']}');
  print('Title: ${saved['title']}');
}
Try it yourself: Change the title and run again.
Edit the title text in the Map.
MEDIUMReal project: search box over server dataExample 8 of 10

Search with refresh

Data is loaded once into a list. A TextField filters it live and a refresh button reloads it. On a real phone you would wrap the list in RefreshIndicator for pull-down refresh.
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> {
  List all = [];
  String q = '';
  bool loading = true;
  Future<void> load() async {
    final r = await http.get(Uri.parse('https://api.brainbit-teaching.com/users'));
    setState(() { all = jsonDecode(r.body); loading = false; });
  }
  @override
  void initState() { super.initState(); load(); }
  @override
  Widget build(BuildContext context) {
    final shown = all.where((u) => u['name'].toLowerCase().contains(q.toLowerCase())).toList();
    return Scaffold(
      appBar: AppBar(title: const Text('Find user'), actions: [IconButton(icon: const Icon(Icons.refresh), onPressed: () { setState(() => loading = true); load(); })]),
      body: Column(children: [
        Padding(padding: const EdgeInsets.all(12), child: TextField(onChanged: (v) => setState(() => q = v), decoration: const InputDecoration(prefixIcon: Icon(Icons.search), hintText: 'Search name', border: OutlineInputBorder()))),
        if (loading) const LinearProgressIndicator(),
        Expanded(child: ListView(children: shown.map((u) => ListTile(title: Text(u['name']), subtitle: Text(u['city']))).toList())),
      ]),
    );
  }
}
void main() => runApp(const MaterialApp(home: Page()));
Try it yourself: Search by city as well as name.
|| u['city'].toLowerCase().contains(...)
HARDReal project: weather appExample 9 of 10

Weather dashboard

City chips call /weather?q=city. A model holds temp, humidity and text. States: loading, data, error (try the city "mars"). A weather icon is chosen by the description.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class Weather {
  final String city, desc; final double temp; final int humidity;
  Weather.fromJson(Map<String, dynamic> j) : city = j['city'], desc = j['desc'], temp = (j['temp'] as num).toDouble(), humidity = j['humidity'];
}
class Page extends StatefulWidget {
  const Page({super.key});
  @override
  State<Page> createState() => _PageState();
}
class _PageState extends State<Page> {
  Future<Weather>? f;
  Future<Weather> load(String c) async {
    final r = await http.get(Uri.parse('https://api.brainbit-teaching.com/weather?q=$c'));
    if (r.statusCode != 200) throw Exception('City not found');
    return Weather.fromJson(jsonDecode(r.body));
  }
  IconData icon(String d) => d.contains('rain') ? Icons.water_drop : d.contains('Clear') ? Icons.wb_sunny : Icons.cloud;
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Weather')),
    body: Column(children: [
      Wrap(spacing: 8, children: ['ranchi', 'patna', 'dhanbad', 'mars'].map((c) => ActionChip(label: Text(c), onPressed: () => setState(() => f = load(c)))).toList()),
      Expanded(child: f == null ? const Center(child: Text('Choose a city')) : FutureBuilder<Weather>(future: f, builder: (c, s) {
        if (s.connectionState != ConnectionState.done) return const Center(child: CircularProgressIndicator());
        if (s.hasError) return Center(child: Text('${s.error}'));
        final w = s.data!;
        return Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
          Icon(icon(w.desc), size: 80, color: Colors.orange),
          Text(w.city, style: const TextStyle(fontSize: 30)),
          Text('${w.temp.toStringAsFixed(1)} C', style: const TextStyle(fontSize: 50)),
          Text('${w.desc}  -  humidity ${w.humidity}%'),
        ]));
      })),
    ]),
  );
}
void main() => runApp(const MaterialApp(home: Page()));
Try it yourself: Add "bokaro" to the chips. What does the app show?
It shows the error because the server has no data for it.
HARDReal project: news / social media feedExample 10 of 10

News feed with states

A complete feed: a loading shimmer-like spinner, a refresh button, an error screen with Retry (the Fail button simulates a server problem) and cards. This is the pattern used by every list-from-API screen.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class Feed extends StatefulWidget {
  const Feed({super.key});
  @override
  State<Feed> createState() => _FeedState();
}
class _FeedState extends State<Feed> {
  String url = 'https://api.brainbit-teaching.com/posts';
  late Future<List<dynamic>> f;
  Future<List<dynamic>> load() async {
    final r = await http.get(Uri.parse(url));
    if (r.statusCode != 200) throw Exception('Server error (${r.statusCode})');
    return jsonDecode(r.body);
  }
  @override
  void initState() { super.initState(); f = load(); }
  void reload(String u) => setState(() { url = u; f = load(); });
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Ranchi Samachar'), actions: [
      IconButton(icon: const Icon(Icons.refresh), onPressed: () => reload(url)),
      TextButton(onPressed: () => reload('https://api.brainbit-teaching.com/fail'), child: const Text('Fail')),
    ]),
    body: FutureBuilder<List<dynamic>>(future: f, builder: (c, s) {
      if (s.connectionState != ConnectionState.done) return const Center(child: CircularProgressIndicator());
      if (s.hasError) return Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
        const Icon(Icons.cloud_off, size: 60, color: Colors.grey),
        Text('${s.error}'),
        ElevatedButton(onPressed: () => reload('https://api.brainbit-teaching.com/posts'), child: const Text('Retry')),
      ]));
      return ListView(children: s.data!.map((p) => Card(
        margin: const EdgeInsets.fromLTRB(10, 6, 10, 0),
        child: ListTile(leading: const Icon(Icons.article), title: Text(p['title']), subtitle: Text(p['body']), trailing: const Icon(Icons.bookmark_border)))).toList());
    }),
  );
}
void main() => runApp(const MaterialApp(home: Feed()));
Try it yourself: Tap Fail, then Retry. What changes between the screens?
Fail switches to the error URL; Retry goes back to /posts.

Quick quiz

3 questions. Click an answer.
Which HTTP method reads data from a server?
POSTGETDELETEPUT
Where should you create the Future for a FutureBuilder?
Inside build() every timeOnce, in initStateIn pubspec.yamlInside Text
What does jsonDecode return for a JSON object?
A MapA WidgetAn intA Future
Score: 0 / 3

Recap: what you learned in Module 14

API

A web address that returns data.

JSON

jsonDecode and jsonEncode.

Model

fromJson makes typed objects.

http

get, post; check statusCode.

FutureBuilder

Loading, data, error: all 3.

Resilience

try/catch, Retry, refresh.

Next: Local Storage: SharedPreferences, SQLite, Hive - Keep data even after the app closes
MODULE 15 · PART 4

Local Storage: SharedPreferences, SQLite, Hive

Keep data even after the app closes
You will learn
  • Know what is lost when an app closes
  • Save small values with SharedPreferences
  • Store lists as JSON text
  • Use SQLite for tables (create, read, update, delete)
  • Use Hive boxes and an offline cache
You will build: a notes app and an offline cache
4 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
💾

Where is this used in real apps?

Open WhatsApp without internet and your old chats are still there. Login stays after restart. Dark mode is remembered. That is local storage.

SharedPreferences

Small settings: name, theme, "remember me", last opened tab.

SQLite

Tables of records: notes, expenses, attendance, products.

Hive

Fast key-value boxes for objects and caches, with very little code.

Notes
📝
Buy milk
Today 8:10
📝
Class timetable
Yesterday
📝
Fee receipt no. 1042
Mon
+

Memory is forgetful

Variables live in RAM. When the app closes, RAM is cleared and everything is lost. To keep data you must write it to the phone storage.

SharedPreferences

A tiny key-value file. Best for a few settings.

SQLite (sqflite)

A real database with tables and queries. Best for lists of records.

Hive

A fast, simple box of key-value data. Good for caches and small objects.

Files

Images, PDFs, big text. Use path_provider for the folder.

These slides simulate phone storage inside your browser. The code is the same as on a real phone.

SharedPreferences

Think of it as a labelled shelf: each key holds one value. getInstance() is async, so use await. Always give a default with ??.

Do not store passwords or big lists here. For secrets use flutter_secure_storage.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

final prefs = await SharedPreferences.getInstance();

// save
await prefs.setString('name', 'Asha');
await prefs.setInt('visits', 5);
await prefs.setBool('dark', true);

// read (returns null if the key is missing)
final name = prefs.getString('name') ?? 'Guest';
final visits = prefs.getInt('visits') ?? 0;

// delete
await prefs.remove('name');

SQLite in 4 steps

A table is like an Excel sheet: columns are fields, rows are records. where: 'id = ?' with whereArgs is the safe way to pass values (no SQL injection).

CRUD = Create (insert), Read (query), Update, Delete. Every data app is CRUD.
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

// 1. open (create the file the first time)
final db = await openDatabase(join(await getDatabasesPath(), 'notes.db'));

// 2. create a table
await db.execute('CREATE TABLE IF NOT EXISTS notes(id INTEGER PRIMARY KEY, title TEXT)');

// 3. insert, query, update, delete
await db.insert('notes', {'title': 'Buy milk'});
final rows = await db.query('notes', orderBy: 'id DESC');
await db.update('notes', {'title': 'Buy curd'}, where: 'id = ?', whereArgs: [1]);
await db.delete('notes', where: 'id = ?', whereArgs: [1]);

Hive boxes

A box is like a Map saved on disk. put, get, delete. No tables, no SQL. It is very fast for small and medium data.

Choose: few settings = SharedPreferences, lists of records = SQLite, quick cache = Hive.
import 'package:hive_flutter/hive_flutter.dart';

await Hive.initFlutter();
final box = await Hive.openBox('settings');

box.put('theme', 'dark');
box.put('user', {'name': 'Asha', 'city': 'Ranchi'});

final theme = box.get('theme', defaultValue: 'light');
box.delete('theme');
print(box.length);

Which storage to use?

A name or on/off setting

SharedPreferences.

Records you search or sort

SQLite.

Cache of API answers

Hive or SharedPreferences with jsonEncode.

Data shared across devices

Cloud: Firebase (next module).

Secrets (tokens)

flutter_secure_storage.

Offline-first apps always read from local storage first, then refresh from the server.

Animated explainer: RAM is erased, storage stays

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

Animated explainer: Offline-first loading

Press Next to walk through it step by step, or Auto play.
EASYReal project: remember the user nameExample 1 of 10

Save and load a name

Type a name and press Save. Run the example again: the name is still there because it was saved with SharedPreferences.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class Name extends StatefulWidget {
  const Name({super.key});
  @override
  State<Name> createState() => _NameState();
}
class _NameState extends State<Name> {
  final c = TextEditingController();
  String saved = '';
  @override
  void initState() { super.initState(); SharedPreferences.getInstance().then((p) => setState(() => saved = p.getString('name') ?? '')); }
  @override
  Widget build(BuildContext context) {
    return Padding(padding: const EdgeInsets.all(20), child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
      TextField(controller: c, decoration: const InputDecoration(labelText: 'Your name')),
      ElevatedButton(onPressed: () async {
        final p = await SharedPreferences.getInstance();
        await p.setString('name', c.text);
        setState(() => saved = c.text);
      }, child: const Text('Save')),
      Text(saved.isEmpty ? 'Nothing saved yet' : 'Hello, $saved!', style: const TextStyle(fontSize: 24)),
    ]));
  }
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Name())));
Try it yourself: Also save the city in a second key.
p.setString('city', ...)
EASYReal project: visit count, score, streakExample 2 of 10

Persistent counter

The counter is loaded in initState and saved after every tap. Close and reopen: it continues from the same number.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class Counter extends StatefulWidget {
  const Counter({super.key});
  @override
  State<Counter> createState() => _CounterState();
}
class _CounterState extends State<Counter> {
  int n = 0;
  @override
  void initState() { super.initState(); SharedPreferences.getInstance().then((p) => setState(() => n = p.getInt('n') ?? 0)); }
  @override
  Widget build(BuildContext context) {
    return Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
      Text('$n', style: const TextStyle(fontSize: 70)),
      ElevatedButton(onPressed: () async {
        setState(() => n++);
        final p = await SharedPreferences.getInstance();
        await p.setInt('n', n);
      }, child: const Text('Add')),
    ]));
  }
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Counter())));
Try it yourself: Add a Reset button that sets it to 0 and saves.
p.setInt('n', 0)
EASYReal project: theme saved between sessionsExample 3 of 10

Remember dark mode

The switch saves a bool. On start it is read back, so the app opens in the mode the user chose last time.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class Mode extends StatefulWidget {
  const Mode({super.key});
  @override
  State<Mode> createState() => _ModeState();
}
class _ModeState extends State<Mode> {
  bool dark = false;
  @override
  void initState() { super.initState(); SharedPreferences.getInstance().then((p) => setState(() => dark = p.getBool('dark') ?? false)); }
  @override
  Widget build(BuildContext context) {
    return Container(color: dark ? Colors.grey.shade900 : Colors.white, child: Center(child: SwitchListTile(
      title: Text('Dark mode', style: TextStyle(color: dark ? Colors.white : Colors.black)), value: dark,
      onChanged: (v) async {
        setState(() => dark = v);
        (await SharedPreferences.getInstance()).setBool('dark', v);
      })));
  }
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Mode())));
Try it yourself: Also save a font size (int) with a Slider.
p.setInt('font', ...)
EASYReal project: save a list of itemsExample 4 of 10

List as JSON text

SharedPreferences stores simple values. A list of Maps becomes text with jsonEncode and comes back with jsonDecode.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class Fav extends StatefulWidget {
  const Fav({super.key});
  @override
  State<Fav> createState() => _FavState();
}
class _FavState extends State<Fav> {
  List<String> items = [];
  @override
  void initState() { super.initState(); SharedPreferences.getInstance().then((p) { final s = p.getString('places'); if (s != null) setState(() => items = List<String>.from(jsonDecode(s))); }); }
  @override
  Widget build(BuildContext context) {
    return Column(children: [
      const SizedBox(height: 30),
      ElevatedButton(onPressed: () async {
        setState(() => items.add('Place ${items.length + 1}'));
        (await SharedPreferences.getInstance()).setString('places', jsonEncode(items));
      }, child: const Text('Add place')),
      Expanded(child: ListView(children: items.map((e) => ListTile(title: Text(e))).toList())),
    ]);
  }
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Fav())));
Try it yourself: Add a Clear button that removes the key.
p.remove('places'); setState(() => items = []);
EASYReal project: stay logged inExample 5 of 10

Remember me login

A checkbox decides whether the user name is saved. Next time the field is already filled. Very common on login screens.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class Login extends StatefulWidget {
  const Login({super.key});
  @override
  State<Login> createState() => _LoginState();
}
class _LoginState extends State<Login> {
  final u = TextEditingController();
  bool remember = true;
  @override
  void initState() { super.initState(); SharedPreferences.getInstance().then((p) => setState(() => u.text = p.getString('user') ?? '')); }
  @override
  Widget build(BuildContext context) {
    return Padding(padding: const EdgeInsets.all(24), child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
      TextField(controller: u, decoration: const InputDecoration(labelText: 'Mobile or email')),
      CheckboxListTile(title: const Text('Remember me'), value: remember, onChanged: (v) => setState(() => remember = v!)),
      ElevatedButton(onPressed: () async {
        final p = await SharedPreferences.getInstance();
        remember ? await p.setString('user', u.text) : await p.remove('user');
      }, child: const Text('Login')),
    ]));
  }
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Login())));
Try it yourself: Show a SnackBar "Saved" after login.
ScaffoldMessenger.of(context).showSnackBar(...)
MEDIUMReal project: simple notes appExample 6 of 10

Notes with SharedPreferences

A notes list kept as a JSON string. Add and delete write the whole list again. Fine for small apps; SQLite is better when data grows.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class Notes extends StatefulWidget {
  const Notes({super.key});
  @override
  State<Notes> createState() => _NotesState();
}
class _NotesState extends State<Notes> {
  List<String> notes = [];
  final c = TextEditingController();
  @override
  void initState() { super.initState(); SharedPreferences.getInstance().then((p) { final s = p.getString('notes'); if (s != null) setState(() => notes = List<String>.from(jsonDecode(s))); }); }
  @override
  Widget build(BuildContext context) {
    Future<void> save() async => (await SharedPreferences.getInstance()).setString('notes', jsonEncode(notes));
    return Padding(padding: const EdgeInsets.all(12), child: Column(children: [
      const SizedBox(height: 30),
      Row(children: [
        Expanded(child: TextField(controller: c, decoration: const InputDecoration(hintText: 'Write a note'))),
        IconButton(icon: const Icon(Icons.add), onPressed: () { if (c.text.isEmpty) return; setState(() => notes.insert(0, c.text)); c.clear(); save(); }),
      ]),
      Expanded(child: ListView.builder(itemCount: notes.length, itemBuilder: (_, i) => ListTile(
        title: Text(notes[i]), trailing: IconButton(icon: const Icon(Icons.delete), onPressed: () { setState(() => notes.removeAt(i)); save(); })))),
    ]));
  }
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Notes())));
Try it yourself: Show the number of notes in a Text.
Text('${notes.length} notes')
MEDIUMReal project: any app with recordsExample 7 of 10

SQLite CRUD

All four database operations in one screen: insert a row, query all rows, update the first row, delete a row. Output is shown in the console so you can see each result.
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

Future<void> main() async {
  final db = await openDatabase(join(await getDatabasesPath(), 'class.db'));
  await db.execute('CREATE TABLE IF NOT EXISTS students(id INTEGER PRIMARY KEY, name TEXT, marks INTEGER)');
  await db.delete('students', where: 'marks >= ?', whereArgs: [0]);

  await db.insert('students', {'name': 'Asha', 'marks': 82});
  await db.insert('students', {'name': 'Rohit', 'marks': 61});
  await db.insert('students', {'name': 'Pooja', 'marks': 45});
  print('After insert: ${(await db.query('students')).length} rows');

  await db.update('students', {'marks': 70}, where: 'name = ?', whereArgs: ['Pooja']);
  final rows = await db.query('students', orderBy: 'marks DESC');
  for (final r in rows) { print('${r['id']}  ${r['name']}  ${r['marks']}'); }

  await db.delete('students', where: 'name = ?', whereArgs: ['Rohit']);
  print('After delete: ${(await db.query('students')).length} rows');
}
Try it yourself: Insert one more student before the update.
await db.insert('students', {'name': 'Imran', 'marks': 77});
MEDIUMReal project: settings and small cachesExample 8 of 10

Hive box

Hive stores Map-like data by key with almost no code. get with defaultValue avoids nulls. Run it twice: the visit counter keeps going up.
import 'package:hive_flutter/hive_flutter.dart';

Future<void> main() async {
  await Hive.initFlutter();
  final box = await Hive.openBox('app');

  final visits = box.get('visits', defaultValue: 0) + 1;
  await box.put('visits', visits);
  await box.put('user', {'name': 'Asha', 'city': 'Ranchi'});

  print('Visits: $visits');
  print('User: ${box.get('user')}');
  print('Keys: ${box.keys.toList()}');
  print('Missing: ${box.get('theme', defaultValue: 'light')}');
}
Try it yourself: Save a list of favourite cities and print it.
await box.put('cities', ['Ranchi', 'Patna']);
HARDReal project: real task / expense / attendance appExample 9 of 10

Todo app with SQLite

A full database-backed app: add, tick and delete tasks stored in a tasks table. A helper reloads the list after each change. This is the shape of every SQLite app.
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

class Todo extends StatefulWidget {
  const Todo({super.key});
  @override
  State<Todo> createState() => _TodoState();
}
class _TodoState extends State<Todo> {
  late Database db;
  List<Map<String, dynamic>> rows = [];
  int n = 0;
  Future<void> reload() async {
    final r = await db.query('tasks', orderBy: 'id DESC');
    setState(() => rows = r);
  }
  @override
  void initState() {
    super.initState();
    openDatabase(join('db', 'todo.db')).then((d) async {
      db = d;
      await db.execute('CREATE TABLE IF NOT EXISTS tasks(id INTEGER PRIMARY KEY, title TEXT, done INTEGER)');
      reload();
    });
  }
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: Text('Tasks (${rows.length})')),
    body: ListView(children: rows.map((r) => CheckboxListTile(
      title: Text(r['title']), value: r['done'] == 1,
      onChanged: (v) async { await db.update('tasks', {'done': v! ? 1 : 0}, where: 'id = ?', whereArgs: [r['id']]); reload(); },
      secondary: IconButton(icon: const Icon(Icons.delete), onPressed: () async { await db.delete('tasks', where: 'id = ?', whereArgs: [r['id']]); reload(); }))).toList()),
    floatingActionButton: FloatingActionButton(
      onPressed: () async { n++; await db.insert('tasks', {'title': 'Task $n', 'done': 0}); reload(); },
      child: const Icon(Icons.add)),
  );
}
void main() => runApp(const MaterialApp(home: Todo()));
Try it yourself: Add a "Delete done tasks" button.
db.delete('tasks', where: 'done = ?', whereArgs: [1]) then reload().
HARDReal project: works without internetExample 10 of 10

Offline cache for an API

Offline-first: read the cached JSON first so the list appears instantly, then call the API and save the fresh copy. Press "Go offline" to see the cached data still shown when the call fails.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

class Page extends StatefulWidget {
  const Page({super.key});
  @override
  State<Page> createState() => _PageState();
}
class _PageState extends State<Page> {
  List users = [];
  String status = 'Loading...';
  String base = 'https://api.brainbit-teaching.com';
  Future<void> load() async {
    final p = await SharedPreferences.getInstance();
    final cached = p.getString('users');
    if (cached != null) setState(() { users = jsonDecode(cached); status = 'Showing saved copy'; });
    try {
      final r = await http.get(Uri.parse('$base/users'));
      await p.setString('users', r.body);
      setState(() { users = jsonDecode(r.body); status = 'Updated from server'; });
    } catch (e) {
      setState(() => status = cached == null ? 'No internet and nothing saved' : 'Offline: showing saved copy');
    }
  }
  @override
  void initState() { super.initState(); load(); }
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Users'), actions: [
      TextButton(onPressed: () { base = base.contains('offline') ? 'https://api.brainbit-teaching.com' : 'https://api.brainbit-teaching.com/offline'; load(); }, child: const Text('Go offline')),
    ]),
    body: Column(children: [
      Container(width: double.infinity, color: Colors.amber.shade100, padding: const EdgeInsets.all(8), child: Text(status)),
      Expanded(child: ListView(children: users.map((u) => ListTile(title: Text(u['name']), subtitle: Text(u['city']))).toList())),
    ]),
  );
}
void main() => runApp(const MaterialApp(home: Page()));
Try it yourself: Show the time of the last update in the status text.
p.setString('time', DateTime.now().toString())

Quick quiz

3 questions. Click an answer.
Which storage is best for a single on/off setting?
SQLiteSharedPreferencesFutureBuilderStack
What does CRUD stand for?
Create, Read, Update, DeleteCopy, Run, Use, DisposeCall, Render, Undo, DrawCache, Retry, Upload, Download
Why use whereArgs in SQLite?
It is faster to typeIt passes values safelyIt deletes the tableIt opens the file
Score: 0 / 3

Recap: what you learned in Module 15

RAM

Lost on close. Save to keep.

SharedPreferences

Small settings by key.

JSON

jsonEncode lists to store them.

SQLite

Tables and CRUD.

Hive

Fast key-value boxes.

Offline-first

Show cache, then refresh.

Next: Firebase: Login and Cloud Database - Real login and online data without writing a server
MODULE 16 · PART 4

Firebase: Login and Cloud Database

Real login and online data without writing a server
You will learn
  • Understand what Firebase gives you
  • Sign up and log in with Firebase Auth
  • Add, read, update and delete in Cloud Firestore
  • Listen to live changes with snapshots()
  • Build chat, attendance and notice-board apps
You will build: a realtime chat and an attendance app
4 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
🔥

Where is this used in real apps?

You want login, a database and live updates but have no server and no time to build one. Firebase gives you all three from Google.

Auth

Email and password, phone OTP, Google sign-in: ready-made and secure.

Firestore

A cloud database that your whole class can read and write.

Realtime

When one phone writes, every other phone updates in a second.

Class Chat
👨
Rohit
Sir, class at 5?
10:42
👩
Asha
Yes, 5 PM
10:43
👨
Vikash
I will join late
10:45
+
💬
Chat
👥
People

What is Firebase?

Firebase is a set of ready-made backend services from Google. Instead of writing and hosting your own server, you call Firebase from Flutter.

Authentication

Users, passwords, login sessions.

Cloud Firestore

A NoSQL database made of collections and documents.

Storage

Photos and files.

Cloud Messaging

Push notifications.

Free tier

The Spark plan is free and enough for learning and small apps.

These slides simulate Firebase in your browser (no account needed). With a real project the same code runs after you add your google-services.json.

Setup in 5 steps

1. Create a project

console.firebase.google.com, Add project, name it e.g. "ranchi-class".

2. Add the Android app

Enter your package name (like in.brainbit.classapp). Download google-services.json into android/app.

3. Install FlutterFire CLI

dart pub global activate flutterfire_cli then flutterfire configure. It creates firebase_options.dart.

4. Add packages

flutter pub add firebase_core firebase_auth cloud_firestore

5. Initialise in main()

await Firebase.initializeApp(); before runApp.

Test mode rules are open for 30 days. Before release, write real security rules (see the last example).

Firebase Auth

Firebase stores the user securely and keeps them logged in between app launches. Errors like wrong password come as exceptions, so always use try/catch.

Never store passwords yourself in SharedPreferences or Firestore.
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

final auth = FirebaseAuth.instance;

// sign up
await auth.createUserWithEmailAndPassword(email: e, password: p);

// log in
await auth.signInWithEmailAndPassword(email: e, password: p);

// who is logged in? (null if nobody)
final user = auth.currentUser;
print(user?.email);

// log out
await auth.signOut();

// listen to login / logout
auth.authStateChanges().listen((user) { /* user or null */ });

Firestore: collections and documents

A collection is a folder, a document is a record (a Map) inside it. No tables or SQL. Documents in one collection can have different fields.

Plan data by screen: design collections around what each screen needs to show.
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

final db = FirebaseFirestore.instance;

// create (auto id)
await db.collection('notices').add({'title': 'Holiday', 'by': 'Admin'});

// read all
final snap = await db.collection('notices').get();
for (final d in snap.docs) { print('${d.id}: ${d.data()}'); }

// update / delete one document
await db.collection('notices').doc(id).update({'title': 'New title'});
await db.collection('notices').doc(id).delete();

// live updates
db.collection('notices').snapshots();   // a Stream

Realtime with StreamBuilder

A Stream is a Future that keeps sending new values. StreamBuilder rebuilds each time a new snapshot arrives, so the screen is always live.

Real use: chat, order tracking, live scores, attendance dashboards.
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

StreamBuilder<QuerySnapshot>(
  stream: FirebaseFirestore.instance
      .collection('messages')
      .orderBy('time')
      .snapshots(),
  builder: (context, snap) {
    if (!snap.hasData) return const CircularProgressIndicator();
    final docs = snap.data!.docs;
    return ListView(children: docs.map((d) => Text(d['text'])).toList());
  },
)

Animated explainer: Firebase Auth flow

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

Animated explainer: Realtime updates

Press Next to walk through it step by step, or Auto play.
EASYReal project: the first line of every Firebase appExample 1 of 10

Initialise Firebase

Firebase.initializeApp() must finish before any other Firebase call. That is why main() becomes async and calls WidgetsFlutterBinding.ensureInitialized() first.
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

Future<void> main() async {
  print('1. Starting app...');
  await Firebase.initializeApp();
  print('2. Firebase is ready');
  print('3. Logged in user: ${FirebaseAuth.instance.currentUser?.email ?? 'nobody'}');
  print('4. Now it is safe to call runApp()');
}
Try it yourself: Print one more line after initializeApp.
print('5. Ready for Firestore');
EASYReal project: registration screenExample 2 of 10

Sign up a user

createUserWithEmailAndPassword creates the account and logs the user in. A bad email or a repeated email throws an exception that we catch. Run it twice to see the second error.
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

Future<void> main() async {
  await Firebase.initializeApp();
  try {
    final cred = await FirebaseAuth.instance.createUserWithEmailAndPassword(
        email: 'asha@ranchi.in', password: 'secret123');
    print('Created: ${cred.user?.email}');
  } catch (e) {
    print('Failed: $e');
  }
  try {
    await FirebaseAuth.instance.createUserWithEmailAndPassword(email: 'not-an-email', password: 'x');
  } catch (e) {
    print('Failed: $e');
  }
}
Try it yourself: Try another valid email.
email: 'rohit@dhanbad.in'
EASYReal project: login screenExample 3 of 10

Log in and log out

signInWithEmailAndPassword logs in. The wrong password throws an exception. signOut clears the session. Create the user first with the previous example.
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

Future<void> main() async {
  await Firebase.initializeApp();
  final auth = FirebaseAuth.instance;
  try { await auth.createUserWithEmailAndPassword(email: 'asha@ranchi.in', password: 'secret123'); } catch (e) {}
  await auth.signOut();

  try {
    await auth.signInWithEmailAndPassword(email: 'asha@ranchi.in', password: 'wrong');
  } catch (e) { print('Login failed: $e'); }

  await auth.signInWithEmailAndPassword(email: 'asha@ranchi.in', password: 'secret123');
  print('Logged in as ${auth.currentUser?.email}');

  await auth.signOut();
  print('After logout: ${auth.currentUser}');
}
Try it yourself: Print the uid of the logged in user.
auth.currentUser?.uid
EASYReal project: save a form to the cloudExample 4 of 10

Firestore: add a document

collection(...).add(map) creates a document with an automatic id. Run it twice: the collection grows to 2.
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

Future<void> main() async {
  await Firebase.initializeApp();
  final notices = FirebaseFirestore.instance.collection('notices');
  final ref = await notices.add({
    'title': 'Holiday on Saturday',
    'by': 'Principal',
    'priority': 1,
  });
  print('Saved with id: ${ref.id}');
  final all = await notices.get();
  print('Total notices now: ${all.docs.length}');
}
Try it yourself: Add a field "class" with value "10-A".
'class': '10-A',
EASYReal project: show a list from the cloudExample 5 of 10

Firestore: read documents

get() reads a whole collection once. Each document has an id and data(). orderBy and where sort and filter on the server.
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

Future<void> main() async {
  await Firebase.initializeApp();
  final c = FirebaseFirestore.instance.collection('students');
  for (final s in [['Asha', 82], ['Rohit', 61], ['Pooja', 45]]) {
    await c.add({'name': s[0], 'marks': s[1]});
  }
  final top = await c.orderBy('marks', descending: true).get();
  for (final d in top.docs) { print('${d.data()['name']}: ${d.data()['marks']}'); }
  final one = await c.where('name', isEqualTo: 'Rohit').get();
  print('Found: ${one.docs.length}');
}
Try it yourself: Order by marks ascending.
orderBy('marks') without descending
MEDIUMReal project: edit or remove a recordExample 6 of 10

Update and delete

Update and delete need the document id. We keep it from add() and then change and finally remove that one document.
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

Future<void> main() async {
  await Firebase.initializeApp();
  final c = FirebaseFirestore.instance.collection('fees');
  final ref = await c.add({'student': 'Rohit', 'paid': 5000, 'due': 7000});
  print('Created: ${(await ref.get()).data()}');

  await c.doc(ref.id).update({'paid': 12000, 'due': 0});
  print('Updated: ${(await c.doc(ref.id).get()).data()}');

  await c.doc(ref.id).delete();
  final check = await c.doc(ref.id).get();
  print('Exists after delete? ${check.exists}');
}
Try it yourself: Update only the due field to 1000.
update({'due': 1000})
MEDIUMReal project: auto redirect to login or homeExample 7 of 10

Auth state listener

A StreamBuilder on authStateChanges() shows Login when nobody is signed in and Home when someone is. No manual navigation needed.
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class Gate extends StatelessWidget {
  const Gate({super.key});
  @override
  Widget build(BuildContext context) => StreamBuilder<User?>(
    stream: FirebaseAuth.instance.authStateChanges(),
    builder: (c, snap) {
      if (snap.data == null) {
        return Scaffold(body: Center(child: ElevatedButton(
          onPressed: () async {
            try { await FirebaseAuth.instance.createUserWithEmailAndPassword(email: 'asha@ranchi.in', password: 'secret123'); }
            catch (e) { await FirebaseAuth.instance.signInWithEmailAndPassword(email: 'asha@ranchi.in', password: 'secret123'); }
          }, child: const Text('Login as Asha'))));
      }
      return Scaffold(
        appBar: AppBar(title: const Text('Home'), actions: [IconButton(icon: const Icon(Icons.logout), onPressed: () => FirebaseAuth.instance.signOut())]),
        body: Center(child: Text('Welcome ${snap.data!.email}', style: const TextStyle(fontSize: 22))));
    },
  );
}
void main() => runApp(const MaterialApp(home: Gate()));
Try it yourself: Show the uid on the home screen as well.
snap.data!.uid
MEDIUMReal project: chat, comments, live feedExample 8 of 10

Realtime chat

snapshots() with a StreamBuilder shows messages live. Send a message and it appears at once. Two phones with the same code would see each other messages.
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class Chat extends StatefulWidget {
  const Chat({super.key});
  @override
  State<Chat> createState() => _ChatState();
}
class _ChatState extends State<Chat> {
  final c = TextEditingController();
  final col = FirebaseFirestore.instance.collection('chat');
  Future<void> send() async {
    if (c.text.trim().isEmpty) return;
    await col.add({'text': c.text.trim(), 'by': 'Asha', 'time': DateTime.now().millisecondsSinceEpoch});
    c.clear();
  }
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Class Chat')),
    body: Column(children: [
      Expanded(child: StreamBuilder<QuerySnapshot>(stream: col.orderBy('time').snapshots(), builder: (ctx, s) {
        if (!s.hasData) return const Center(child: CircularProgressIndicator());
        return ListView(children: s.data!.docs.map((d) => ListTile(title: Text(d['text']), subtitle: Text(d['by']))).toList());
      })),
      Padding(padding: const EdgeInsets.all(8), child: Row(children: [
        Expanded(child: TextField(controller: c, decoration: const InputDecoration(hintText: 'Type a message'), onSubmitted: (_) => send())),
        IconButton(icon: const Icon(Icons.send), onPressed: send),
      ])),
    ]),
  );
}
void main() => runApp(const MaterialApp(home: Chat()));
Try it yourself: Show the time of each message in the subtitle.
DateTime.fromMillisecondsSinceEpoch(d['time'])
HARDReal project: school attendance / employee check-inExample 9 of 10

Attendance app

A teacher marks each student present or absent. Each tap writes one document (student + date + status) and a live StreamBuilder counts present students. The same pattern as a geo-tagged employee app.
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class Attend extends StatelessWidget {
  const Attend({super.key});
  @override
  Widget build(BuildContext context) {
    final col = FirebaseFirestore.instance.collection('attendance');
    final students = ['Asha', 'Rohit', 'Pooja', 'Vikash'];
    return Scaffold(
      appBar: AppBar(title: const Text('Class 10-A  Attendance')),
      body: StreamBuilder<QuerySnapshot>(stream: col.snapshots(), builder: (c, s) {
        final docs = s.hasData ? s.data!.docs : [];
        String status(String n) { String r = '-'; for (final d in docs) { if (d['name'] == n) r = d['status']; } return r; }
        final present = students.where((n) => status(n) == 'Present').length;
        return Column(children: [
          Container(width: double.infinity, color: Colors.green.shade50, padding: const EdgeInsets.all(12), child: Text('Present: $present / ${students.length}', style: const TextStyle(fontSize: 20))),
          ...students.map((n) => ListTile(
            title: Text(n), subtitle: Text(status(n)),
            trailing: Row(mainAxisSize: MainAxisSize.min, children: [
              IconButton(icon: const Icon(Icons.check_circle, color: Colors.green), onPressed: () => col.doc(n).set({'name': n, 'status': 'Present'})),
              IconButton(icon: const Icon(Icons.cancel, color: Colors.red), onPressed: () => col.doc(n).set({'name': n, 'status': 'Absent'})),
            ]))),
        ]);
      }),
    );
  }
}
void main() => runApp(const MaterialApp(home: Attend()));
Try it yourself: Add a fifth student "Imran".
Add the name to the students list.
HARDReal project: admin posts, students readExample 10 of 10

Notice board with roles

Two roles: Admin can post notices, Student only reads. The role comes from a users collection. In a real project you would also enforce this with Firestore security rules, shown below the app.
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class Board extends StatefulWidget {
  const Board({super.key});
  @override
  State<Board> createState() => _BoardState();
}
class _BoardState extends State<Board> {
  String role = 'Student';
  final col = FirebaseFirestore.instance.collection('notices');
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Notice Board'), actions: [
      TextButton(onPressed: () => setState(() => role = role == 'Admin' ? 'Student' : 'Admin'), child: Text(role, style: const TextStyle(color: Colors.white))),
    ]),
    body: StreamBuilder<QuerySnapshot>(stream: col.snapshots(), builder: (c, s) {
      final docs = s.hasData ? s.data!.docs : [];
      return ListView(children: docs.map((d) => ListTile(
        leading: const Icon(Icons.campaign), title: Text(d['title']),
        trailing: role == 'Admin' ? IconButton(icon: const Icon(Icons.delete), onPressed: () => col.doc(d.id).delete()) : null)).toList());
    }),
    floatingActionButton: role == 'Admin' ? FloatingActionButton(
      onPressed: () => col.add({'title': 'Notice ${DateTime.now().second}'}), child: const Icon(Icons.add)) : null,
  );
}
// Firestore security rules (Firebase console > Rules):
// match /notices/{id} {
//   allow read: if request.auth != null;
//   allow write: if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == 'admin';
// }
void main() => runApp(const MaterialApp(home: Board()));
Try it yourself: Make the Student see a small text "Read only".
if (role == 'Student') Text('Read only')

Quick quiz

3 questions. Click an answer.
In Firestore a record is called a...
TableDocumentRowSheet
What must you call before any other Firebase function?
Firebase.initializeApp()signOut()runApp twicejsonDecode
Which widget shows live changes from Firestore?
TextStreamBuilderPaddingDivider
Score: 0 / 3

Recap: what you learned in Module 16

Firebase

Auth + Firestore + more, no server to write.

Setup

Project, google-services.json, flutterfire configure.

Auth

Sign up, log in, signOut, authStateChanges.

Firestore

Collections and documents: add, get, update, delete.

Realtime

snapshots() + StreamBuilder.

Security

Roles and security rules before release.

Next: the next part of the course.

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