COMPLETE FLUTTER COURSE · BRAINBIT INFOTECH

Part 3

4 modules · 16 class hours · 40 practical examples

Module 9: State and setState: Making Apps Interactive

Apps that react when you tap · 4 h

Module 10: Forms and User Input

Collect and check what the user types · 4 h

Module 11: Navigation: Many Screens, One App

Move between screens, dialogs and tabs · 4 h

Module 12: Animations, Themes and Responsive UI

Make the app beautiful and alive · 4 h

MODULE 9 · PART 3

State and setState: Making Apps Interactive

Apps that react when you tap
You will learn
  • Understand Stateless vs Stateful widgets
  • Change the screen with setState()
  • Keep counters, toggles and lists in state
  • Handle taps with onPressed and onTap
  • Build small games and tools that react to the user
You will build: a quiz app and a tic-tac-toe game
4 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
⚡

Where is this used in real apps?

A like button turns red, a cart total changes, a quiz shows the next question: all of that is state changing.

State

Data that can change while the app runs: a counter, a switch, the items in a cart.

setState

Tells Flutter: data changed, redraw the screen.

Everywhere

Likes, quantity buttons, dark mode switches, tabs, quizzes, games.

Cart
🥔
Atta 5 kg - 1 +
Rs 245
🥛
Rice 10 kg - 2 +
Rs 760
🥛
Dal 1 kg - 1 +
Rs 140

Stateless vs Stateful

A StatelessWidget never changes after it is drawn: a logo, a title. A StatefulWidget has data that changes: a counter, a switch.

StatelessWidget

Only build(). Same input, same picture.

StatefulWidget

Two classes: the widget and its State. Data lives in the State class.

How to choose

Does anything on this widget change when the user taps? Yes: Stateful.

Tip: In VS Code type stful and press Enter. The whole skeleton appears.

Your first StatefulWidget

The number lives in the State class. Pressing the button runs setState, Flutter calls build() again, and the new number appears.

Golden rule: change variables inside setState. If you change them outside, the screen does not update.
class Counter extends StatefulWidget {
  const Counter({super.key});
  @override
  State<Counter> createState() => _CounterState();
}

class _CounterState extends State<Counter> {
  int count = 0;                       // the state

  @override
  Widget build(BuildContext context) {
    return Column(mainAxisAlignment: MainAxisAlignment.center, children: [
      Text('$count', style: const TextStyle(fontSize: 56)),
      ElevatedButton(
        onPressed: () {
          setState(() { count++; });   // change + redraw
        },
        child: const Text('Add one'),
      ),
    ]);
  }
}

void main() {
  runApp(const MaterialApp(home: Scaffold(body: Counter())));
}

What setState really does

1. You tap

onPressed runs your code.

2. You change data

Inside setState(() { ... }) you change the variable.

3. Flutter marks it dirty

This widget needs a new picture.

4. build() runs again

The widget is rebuilt with the new data and the screen updates.

Only the widget with setState (and its children) rebuilds, not the whole app.

Booleans and lists as state

State is not only numbers. A bool remembers on/off. A List remembers cart items or tasks. Any change inside setState redraws.

Real use: liked = true turns the heart red; items.add adds a row to the todo list.
bool liked = false;
List<String> items = [];

// toggle
setState(() => liked = !liked);

// add to a list
setState(() => items.add('New task'));

// remove from a list
setState(() => items.removeAt(0));

Showing and hiding with if

Inside children you can write if (condition) Widget. The widget appears only when the state says so. The ? : operator chooses between two widgets.

Real use: show an error message only when the form is wrong; show a loader only while loading.
Column(children: [
  Switch(value: show, onChanged: (v) => setState(() => show = v)),
  if (show) const Text('Hello, I am visible'),
  show ? const Icon(Icons.visibility) : const Icon(Icons.visibility_off),
])

Animated explainer: The setState cycle

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

Animated explainer: Stateless or Stateful?

Press Next to walk through it step by step, or Auto play.
EASYReal project: quantity counter, attendance counterExample 1 of 10

Counter app

The classic first Flutter app. One int in State and a button that adds one with setState.
class Counter extends StatefulWidget {
  const Counter({super.key});
  @override
  State<Counter> createState() => _CounterState();
}
class _CounterState extends State<Counter> {
  int count = 0;
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Counter')),
    body: Center(child: Text('$count', style: const TextStyle(fontSize: 64))),
    floatingActionButton: FloatingActionButton(
      onPressed: () => setState(() => count++),
      child: const Icon(Icons.add),
    ),
  );
}
void main() => runApp(const MaterialApp(home: Counter()));
Try it yourself: Add a second button that subtracts one.
Add another FloatingActionButton or an IconButton with count--.
EASYReal project: like / favourite heartExample 2 of 10

Like button

A bool in state decides the icon and colour. Tapping flips the bool with !liked.
class Like extends StatefulWidget {
  const Like({super.key});
  @override
  State<Like> createState() => _LikeState();
}
class _LikeState extends State<Like> {
  bool liked = false;
  @override
  Widget build(BuildContext context) => Scaffold(
    body: Center(child: IconButton(
      iconSize: 80,
      icon: Icon(liked ? Icons.favorite : Icons.favorite_border,
          color: liked ? Colors.red : Colors.grey),
      onPressed: () => setState(() => liked = !liked),
    )),
  );
}
void main() => runApp(const MaterialApp(home: Like()));
Try it yourself: Show text "Liked" below the heart when liked.
Wrap in a Column and add if (liked) Text('Liked').
EASYReal project: password show/hide, FAQ answersExample 3 of 10

Show and hide

A bool controls whether a widget exists. if (show) inside children adds or removes it.
class Faq extends StatefulWidget {
  const Faq({super.key});
  @override
  State<Faq> createState() => _FaqState();
}
class _FaqState extends State<Faq> {
  bool open = false;
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('FAQ')),
    body: Padding(padding: const EdgeInsets.all(20), child: Column(children: [
      ListTile(
        title: const Text('What is the course fee?'),
        trailing: Icon(open ? Icons.expand_less : Icons.expand_more),
        onTap: () => setState(() => open = !open),
      ),
      if (open) const Text('The fee is Rs 24,000 and can be paid in 3 instalments.'),
    ])),
  );
}
void main() => runApp(const MaterialApp(home: Faq()));
Try it yourself: Add a second question with its own bool.
Make bool open2 and copy the ListTile and if.
EASYReal project: settings page theme switchExample 4 of 10

Dark mode switch

A Switch reports its new value in onChanged. Store it in state and use it to choose colours.
class Mode extends StatefulWidget {
  const Mode({super.key});
  @override
  State<Mode> createState() => _ModeState();
}
class _ModeState extends State<Mode> {
  bool dark = false;
  @override
  Widget build(BuildContext context) => Scaffold(
    backgroundColor: dark ? Colors.grey.shade900 : Colors.white,
    body: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
      Icon(dark ? Icons.dark_mode : Icons.light_mode, size: 60, color: dark ? Colors.yellow : Colors.orange),
      Text(dark ? 'Night' : 'Day', style: TextStyle(fontSize: 30, color: dark ? Colors.white : Colors.black)),
      Switch(value: dark, onChanged: (v) => setState(() => dark = v)),
    ])),
  );
}
void main() => runApp(const MaterialApp(home: Mode()));
Try it yourself: Change the dark colour to Colors.indigo.shade900.
Edit backgroundColor for dark.
EASYReal project: add-to-cart + / - buttonsExample 5 of 10

Quantity selector

Two buttons change one number. if (qty > 1) stops it going below 1. The price is calculated from the state.
class Qty extends StatefulWidget {
  const Qty({super.key});
  @override
  State<Qty> createState() => _QtyState();
}
class _QtyState extends State<Qty> {
  int qty = 1;
  final int price = 245;
  @override
  Widget build(BuildContext context) => Scaffold(
    body: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
      const Text('Atta 5 kg', style: TextStyle(fontSize: 24)),
      Row(mainAxisSize: MainAxisSize.min, children: [
        IconButton(icon: const Icon(Icons.remove_circle), onPressed: () { if (qty > 1) setState(() => qty--); }),
        Text('$qty', style: const TextStyle(fontSize: 28)),
        IconButton(icon: const Icon(Icons.add_circle), onPressed: () => setState(() => qty++)),
      ]),
      Text('Total: Rs ${qty * price}', style: const TextStyle(fontSize: 20, color: Colors.green)),
    ])),
  );
}
void main() => runApp(const MaterialApp(home: Qty()));
Try it yourself: Stop quantity going above 10.
In the + button: if (qty < 10) setState(() => qty++).
MEDIUMReal project: shopping cartExample 6 of 10

Cart total

A list of items with quantities. Each item has its own + and -. The grand total is calculated every time build() runs, so it is always correct.
class Cart extends StatefulWidget {
  const Cart({super.key});
  @override
  State<Cart> createState() => _CartState();
}
class _CartState extends State<Cart> {
  final names = ['Atta 5 kg', 'Rice 10 kg', 'Dal 1 kg'];
  final prices = [245, 380, 140];
  final qty = [1, 1, 1];
  @override
  Widget build(BuildContext context) {
    int total = 0;
    for (var i = 0; i < names.length; i++) { total += prices[i] * qty[i]; }
    return Scaffold(
      appBar: AppBar(title: const Text('Cart')),
      body: Column(children: [
        for (var i = 0; i < names.length; i++) ListTile(
          title: Text(names[i]), subtitle: Text('Rs ${prices[i]}'),
          trailing: Row(mainAxisSize: MainAxisSize.min, children: [
            IconButton(icon: const Icon(Icons.remove), onPressed: () => setState(() { if (qty[i] > 0) qty[i]--; })),
            Text('${qty[i]}'),
            IconButton(icon: const Icon(Icons.add), onPressed: () => setState(() => qty[i]++)),
          ])),
        const Divider(),
        Text('Total: Rs $total', style: const TextStyle(fontSize: 22, fontWeight: FontWeight.bold)),
      ]),
    );
  }
}
void main() => runApp(const MaterialApp(home: Cart()));
Try it yourself: Add "Sugar 1 kg" at Rs 48.
Add to names, prices and qty lists.
MEDIUMReal project: category tabs, filtersExample 7 of 10

Tabs with state

The selected tab number is state. Chips change it with setState, and the content below changes to match.
class Tabs extends StatefulWidget {
  const Tabs({super.key});
  @override
  State<Tabs> createState() => _TabsState();
}
class _TabsState extends State<Tabs> {
  int sel = 0;
  final tabs = ['Food', 'Drinks', 'Sweets'];
  final data = [['Litti', 'Dhuska'], ['Lassi', 'Sattu sharbat'], ['Thekua', 'Peda']];
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Menu')),
    body: Column(children: [
      Row(mainAxisAlignment: MainAxisAlignment.center, children: [
        for (var i = 0; i < tabs.length; i++) Padding(padding: const EdgeInsets.all(6),
          child: ChoiceChip(label: Text(tabs[i]), selected: sel == i, onSelected: (_) => setState(() => sel = i))),
      ]),
      for (final d in data[sel]) ListTile(leading: const Icon(Icons.restaurant), title: Text(d)),
    ]),
  );
}
void main() => runApp(const MaterialApp(home: Tabs()));
Try it yourself: Add a fourth tab "Combos" with 2 items.
Add to tabs and data.
MEDIUMReal project: task manager, notes appExample 8 of 10

Todo list

State is a List. Adding and removing items calls setState, and ListView.builder shows the latest list. The most common beginner project.
class Todo extends StatefulWidget {
  const Todo({super.key});
  @override
  State<Todo> createState() => _TodoState();
}
class _TodoState extends State<Todo> {
  final tasks = ['Buy vegetables', 'Finish Flutter homework'];
  int n = 0;
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: Text('Tasks (${tasks.length})')),
    body: ListView.builder(
      itemCount: tasks.length,
      itemBuilder: (c, i) => ListTile(
        title: Text(tasks[i]),
        trailing: IconButton(icon: const Icon(Icons.delete, color: Colors.red),
            onPressed: () => setState(() => tasks.removeAt(i))),
      ),
    ),
    floatingActionButton: FloatingActionButton(
      onPressed: () => setState(() { n++; tasks.add('New task $n'); }),
      child: const Icon(Icons.add),
    ),
  );
}
void main() => runApp(const MaterialApp(home: Todo()));
Try it yourself: Add a "Clear all" button using tasks.clear().
IconButton in AppBar actions with setState(() => tasks.clear()).
HARDReal project: MCQ test, exam practice appExample 9 of 10

Quiz app

Question number, score and finished flag are all state. After the last question a result screen is shown with the percentage.
class Quiz extends StatefulWidget {
  const Quiz({super.key});
  @override
  State<Quiz> createState() => _QuizState();
}
class _QuizState extends State<Quiz> {
  final qs = [
    ['Capital of Jharkhand?', 'Ranchi', 'Patna', 'Dhanbad', '0'],
    ['Flutter uses which language?', 'Java', 'Dart', 'Swift', '1'],
    ['State change method?', 'setState', 'runApp', 'build', '0'],
  ];
  int i = 0, score = 0;
  void pick(int a) => setState(() { if (a == int.parse(qs[i][4])) score++; i++; });
  @override
  Widget build(BuildContext context) {
    if (i >= qs.length) {
      return Scaffold(body: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
        const Icon(Icons.emoji_events, size: 70, color: Colors.amber),
        Text('Score: $score / ${qs.length}', style: const TextStyle(fontSize: 28)),
        Text('${(score * 100 / qs.length).toStringAsFixed(0)}%'),
        ElevatedButton(onPressed: () => setState(() { i = 0; score = 0; }), child: const Text('Try again')),
      ])));
    }
    return Scaffold(
      appBar: AppBar(title: Text('Question ${i + 1} of ${qs.length}')),
      body: Padding(padding: const EdgeInsets.all(20), child: Column(children: [
        LinearProgressIndicator(value: i / qs.length),
        const SizedBox(height: 24),
        Text(qs[i][0], style: const TextStyle(fontSize: 22)),
        const SizedBox(height: 16),
        for (var k = 1; k <= 3; k++) Padding(padding: const EdgeInsets.only(bottom: 8),
          child: SizedBox(width: double.infinity, child: OutlinedButton(onPressed: () => pick(k - 1), child: Text(qs[i][k])))),
      ])),
    );
  }
}
void main() => runApp(const MaterialApp(home: Quiz()));
Try it yourself: Add a 4th question of your own.
Add a list: [question, opt1, opt2, opt3, correctIndex].
HARDReal project: game logic and grid stateExample 10 of 10

Tic-tac-toe

The board is a list of 9 cells in state. A tap puts X or O, then a function checks the 8 winning lines. Game logic plus UI in under 60 lines.
class Game extends StatefulWidget {
  const Game({super.key});
  @override
  State<Game> createState() => _GameState();
}
class _GameState extends State<Game> {
  List<String> b = List.filled(9, '');
  bool xTurn = true;
  String winner = '';
  final lines = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]];
  void tap(int i) {
    if (b[i] != '' || winner != '') return;
    setState(() {
      b[i] = xTurn ? 'X' : 'O';
      xTurn = !xTurn;
      for (final l in lines) {
        if (b[l[0]] != '' && b[l[0]] == b[l[1]] && b[l[1]] == b[l[2]]) winner = b[l[0]];
      }
    });
  }
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: Text(winner != '' ? '$winner wins!' : (xTurn ? 'X turn' : 'O turn'))),
    body: Column(children: [
      Expanded(child: GridView.count(crossAxisCount: 3, padding: const EdgeInsets.all(16),
        crossAxisSpacing: 6, mainAxisSpacing: 6,
        children: [for (var i = 0; i < 9; i++) InkWell(onTap: () => tap(i),
          child: Container(color: Colors.indigo.shade50, alignment: Alignment.center,
              child: Text(b[i], style: const TextStyle(fontSize: 44))))])),
      ElevatedButton(onPressed: () => setState(() { b = List.filled(9, ''); winner = ''; xTurn = true; }), child: const Text('Reset')),
    ]),
  );
}
void main() => runApp(const MaterialApp(home: Game()));
Try it yourself: Show "Draw" when all 9 cells are full and nobody won.
Check !b.contains('') && winner == '' and set winner = 'Nobody'.

Quick quiz

3 questions. Click an answer.
Which widget type holds data that can change?
StatelessWidgetStatefulWidgetContainerText
Where should you change a variable so the screen updates?
AnywhereInside setStateIn main()In pubspec.yaml
What happens after setState is called?
App closesbuild() runs againNothingData is deleted
Score: 0 / 3

Recap: what you learned in Module 9

Stateful

Use it when data changes after a tap.

setState

Change data inside it, build() runs again.

bool

Switches, likes, show/hide.

List

Todo and cart items.

if / ? :

Show widgets depending on state.

Games

State + logic = tic-tac-toe, quiz.

Next: Forms and User Input - Collect and check what the user types
MODULE 10 · PART 3

Forms and User Input

Collect and check what the user types
You will learn
  • Read text with TextField and TextEditingController
  • Use Checkbox, Switch, Radio and Dropdown
  • Validate input with Form and validator
  • Use Slider and pickers for numbers
  • Build a complete admission form
You will build: an admission form and a multi-step registration
4 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
📝

Where is this used in real apps?

Sign up, login, checkout, feedback, admission: every real app collects input, and wrong input must be caught before it reaches the server.

TextField

Name, mobile number, email, password.

Choices

Checkbox for terms, Radio for gender, Dropdown for city.

Validation

Show "Enter 10 digit mobile number" before submit.

Admission Form
👤
Student name
Type here
📞
Mobile number
10 digits
🏫
Course
Select
+
📝
Form
✓
Done

TextField and controller

A TextEditingController holds what the user typed. Read it with controller.text when the button is pressed.

keyboardType chooses the keyboard: TextInputType.phone, .emailAddress, .number. obscureText: true hides a password.
final nameCtrl = TextEditingController();

TextField(
  controller: nameCtrl,
  decoration: const InputDecoration(
    labelText: 'Student name',
    hintText: 'e.g. Rohit Singh',
    prefixIcon: Icon(Icons.person),
    border: OutlineInputBorder(),
  ),
)

// read the text later
print(nameCtrl.text);

onChanged: react while typing

onChanged runs on every key press. Use it for live search, character counters and live previews.

Real use: search box that filters a list as you type.
TextField(
  onChanged: (value) {
    setState(() => name = value);
  },
)
Text('Hello, $name!')

Checkbox, Switch, Radio

Checkbox

Checkbox(value: agree, onChanged: (v) => setState(() => agree = v!)): yes/no, can pick many.

Switch

An on/off setting: notifications, dark mode.

Radio

Pick exactly ONE of a group: gender, payment method. All radios share one groupValue.

Dropdown

DropdownButton chooses one item from a long list: city, class.

Rule: each of these only shows a value. You keep the value in state and update it in onChanged.

Form and validation

A validator returns an error text, or null when the value is fine. validate() runs all validators and shows the red messages.

Real use: never send empty or wrong data to the server. Validate first.
final key = GlobalKey<FormState>();

Form(
  key: key,
  child: Column(children: [
    TextFormField(
      validator: (v) {
        if (v == null || v.length != 10) return 'Enter 10 digit mobile number';
        return null;                 // null means OK
      },
    ),
    ElevatedButton(
      onPressed: () {
        if (key.currentState!.validate()) { /* submit */ }
      },
      child: const Text('Submit'),
    ),
  ]),
)

Slider and pickers

Slider

Slider(value: v, min: 0, max: 100, onChanged: ...): volume, price range, marks.

showDatePicker

Opens a calendar to pick a date of birth or a booking day.

showTimePicker

Pick a time for an appointment reminder.

Why pickers

Pickers prevent typing mistakes like "32/13/2020".

Tip: use a picker whenever the answer must be one valid value.

Animated explainer: How a TextField gives you text

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

Animated explainer: Validation flow

Press Next to walk through it step by step, or Auto play.
EASYReal project: any single input: name, searchExample 1 of 10

TextField with controller

The controller gives you the text on button press. The text is shown in a Text widget below.
class NameBox extends StatefulWidget {
  const NameBox({super.key});
  @override
  State<NameBox> createState() => _NameBoxState();
}
class _NameBoxState extends State<NameBox> {
  final c = TextEditingController();
  String shown = '';
  @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', border: OutlineInputBorder())),
      const SizedBox(height: 12),
      ElevatedButton(onPressed: () => setState(() => shown = c.text), child: const Text('Show')),
      Text(shown, style: const TextStyle(fontSize: 24)),
    ]));
  }
}
void main() => runApp(const MaterialApp(home: Scaffold(body: NameBox())));
Try it yourself: Show the text in capital letters.
shown = c.text.toUpperCase()
EASYReal project: live search, live previewExample 2 of 10

Live greeting with onChanged

onChanged runs on every letter. The greeting updates while you type, no button needed.
class Live extends StatefulWidget {
  const Live({super.key});
  @override
  State<Live> createState() => _LiveState();
}
class _LiveState extends State<Live> {
  String name = '';
  @override
  Widget build(BuildContext context) {
    return Padding(padding: const EdgeInsets.all(20), child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
      TextField(onChanged: (v) => setState(() => name = v), decoration: const InputDecoration(labelText: 'Type your name')),
      const SizedBox(height: 20),
      Text(name.isEmpty ? 'Hello!' : 'Hello, $name!', style: const TextStyle(fontSize: 28)),
      Text('${name.length} letters'),
    ]));
  }
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Live())));
Try it yourself: Hide the letter count when the box is empty.
if (name.isNotEmpty) Text(...)
EASYReal project: terms and conditions, to-do ticksExample 3 of 10

Checkbox: accept terms

The Checkbox value is a bool in state. The button stays disabled (onPressed: null) until the box is ticked.
class Terms extends StatefulWidget {
  const Terms({super.key});
  @override
  State<Terms> createState() => _TermsState();
}
class _TermsState extends State<Terms> {
  bool agree = false;
  @override
  Widget build(BuildContext context) {
    return Padding(padding: const EdgeInsets.all(20), child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
      CheckboxListTile(
        title: const Text('I accept the terms and conditions'),
        value: agree,
        onChanged: (v) => setState(() => agree = v!),
      ),
      ElevatedButton(onPressed: agree ? () {} : null, child: const Text('Continue')),
    ]));
  }
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Terms())));
Try it yourself: Add a second checkbox "Send me offers".
Another bool and CheckboxListTile.
EASYReal project: notification settings pageExample 4 of 10

Switch settings

Each SwitchListTile is one setting, backed by one bool. The subtitle explains the current state.
class Settings extends StatefulWidget {
  const Settings({super.key});
  @override
  State<Settings> createState() => _SettingsState();
}
class _SettingsState extends State<Settings> {
  bool notify = true;
  bool sound = false;
  @override
  Widget build(BuildContext context) {
    return ListView(children: [
      SwitchListTile(title: const Text('Notifications'), subtitle: Text(notify ? 'On' : 'Off'), value: notify, onChanged: (v) => setState(() => notify = v)),
      SwitchListTile(title: const Text('Sound'), subtitle: Text(sound ? 'On' : 'Off'), value: sound, onChanged: (v) => setState(() => sound = v)),
    ]);
  }
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Settings())));
Try it yourself: Add a "Vibrate" switch.
New bool and SwitchListTile.
EASYReal project: gender, payment method, shiftExample 5 of 10

Radio buttons

Radios in a group share groupValue. Selecting one changes it, so only one is on at a time.
class Pay extends StatefulWidget {
  const Pay({super.key});
  @override
  State<Pay> createState() => _PayState();
}
class _PayState extends State<Pay> {
  String method = 'UPI';
  @override
  Widget build(BuildContext context) {
    return Column(mainAxisAlignment: MainAxisAlignment.center, children: [
      const Text('Payment method', style: TextStyle(fontSize: 22)),
      RadioListTile<String>(title: const Text('UPI'), value: 'UPI', groupValue: method, onChanged: (v) => setState(() => method = v!)),
      RadioListTile<String>(title: const Text('Card'), value: 'Card', groupValue: method, onChanged: (v) => setState(() => method = v!)),
      RadioListTile<String>(title: const Text('Cash on delivery'), value: 'COD', groupValue: method, onChanged: (v) => setState(() => method = v!)),
      Text('You chose: $method'),
    ]);
  }
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Pay())));
Try it yourself: Add "Net banking".
Copy a RadioListTile with a new value.
MEDIUMReal project: choose course / city / classExample 6 of 10

Dropdown with fee

DropdownButton lists items. The chosen value decides the fee shown below. A Map keeps course names and fees together.
class Fee extends StatefulWidget {
  const Fee({super.key});
  @override
  State<Fee> createState() => _FeeState();
}
class _FeeState extends State<Fee> {
  final fees = {'Flutter': 18000, 'Python': 15000, 'Web Design': 12000};
  String course = 'Flutter';
  @override
  Widget build(BuildContext context) {
    return Padding(padding: const EdgeInsets.all(24), child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
      DropdownButton<String>(
        value: course,
        isExpanded: true,
        items: fees.keys.map((k) => DropdownMenuItem(value: k, child: Text(k))).toList(),
        onChanged: (v) => setState(() => course = v!),
      ),
      const SizedBox(height: 20),
      Text('Fee: Rs ${fees[course]}', style: const TextStyle(fontSize: 26, color: Colors.green)),
    ]));
  }
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Fee())));
Try it yourself: Add "Java": 14000.
Add the entry to the fees map.
MEDIUMReal project: login, signup, any submitExample 7 of 10

Form with validation

Each TextFormField has a validator. validate() shows red errors for bad fields and returns true only when all are good.
class Signup extends StatefulWidget {
  const Signup({super.key});
  @override
  State<Signup> createState() => _SignupState();
}
class _SignupState extends State<Signup> {
  final key = GlobalKey<FormState>();
  String msg = '';
  @override
  Widget build(BuildContext context) {
    return Form(key: key, child: Padding(padding: const EdgeInsets.all(20), child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
      TextFormField(decoration: const InputDecoration(labelText: 'Mobile number'), keyboardType: TextInputType.phone,
        validator: (v) => (v == null || v.length != 10) ? 'Enter 10 digit mobile number' : null),
      TextFormField(decoration: const InputDecoration(labelText: 'Password'), obscureText: true,
        validator: (v) => (v == null || v.length < 6) ? 'At least 6 characters' : null),
      const SizedBox(height: 16),
      ElevatedButton(onPressed: () => setState(() => msg = key.currentState!.validate() ? 'Form is valid' : 'Please fix errors'), child: const Text('Sign up')),
      Text(msg),
    ])));
  }
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Signup())));
Try it yourself: Add an email field that must contain "@".
validator: (v) => v!.contains('@') ? null : 'Invalid email'
MEDIUMReal project: price filter, volume, ratingExample 8 of 10

Slider for marks or price

Slider gives a number between min and max. divisions makes it jump in steps and label shows the value above the thumb.
class Marks extends StatefulWidget {
  const Marks({super.key});
  @override
  State<Marks> createState() => _MarksState();
}
class _MarksState extends State<Marks> {
  double marks = 60;
  @override
  Widget build(BuildContext context) {
    final grade = marks >= 75 ? 'A' : marks >= 50 ? 'B' : 'C';
    return Padding(padding: const EdgeInsets.all(24), child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
      Text('Marks: ${marks.round()}', style: const TextStyle(fontSize: 28)),
      Slider(value: marks, min: 0, max: 100, divisions: 20, label: '${marks.round()}', onChanged: (v) => setState(() => marks = v)),
      Text('Grade $grade', style: const TextStyle(fontSize: 36, color: Colors.indigo)),
    ]));
  }
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Marks())));
Try it yourself: Make grade A start at 80.
marks >= 80
HARDReal project: school / coaching admission appExample 9 of 10

Admission form

A full form: name, mobile, class dropdown, gender radios, terms checkbox, validation, and a confirmation card after Submit. Everything from this module together.
class Admission extends StatefulWidget {
  const Admission({super.key});
  @override
  State<Admission> createState() => _AdmissionState();
}
class _AdmissionState extends State<Admission> {
  final key = GlobalKey<FormState>();
  final name = TextEditingController();
  String cls = 'Class 10';
  String gender = 'Male';
  bool agree = false;
  String done = '';
  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(padding: const EdgeInsets.all(18), child: Form(key: key, child: Column(children: [
      const SizedBox(height: 30),
      TextFormField(controller: name, decoration: const InputDecoration(labelText: 'Student name', border: OutlineInputBorder()),
        validator: (v) => v!.trim().isEmpty ? 'Name is required' : null),
      const SizedBox(height: 10),
      DropdownButtonFormField<String>(value: cls, items: ['Class 8', 'Class 9', 'Class 10'].map((e) => DropdownMenuItem(value: e, child: Text(e))).toList(), onChanged: (v) => setState(() => cls = v!)),
      Row(children: [for (final g in ['Male', 'Female']) Expanded(child: RadioListTile<String>(title: Text(g), value: g, groupValue: gender, onChanged: (v) => setState(() => gender = v!)))]),
      CheckboxListTile(title: const Text('I agree to the rules'), value: agree, onChanged: (v) => setState(() => agree = v!)),
      ElevatedButton(onPressed: () {
        if (key.currentState!.validate() && agree) setState(() => done = 'Admitted: ${name.text} ($gender), $cls');
      }, child: const Text('Submit')),
      if (done != '') Card(color: Colors.green.shade50, child: Padding(padding: const EdgeInsets.all(12), child: Text(done))),
    ])));
  }
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Admission())));
Try it yourself: Add a "Father name" field with validation.
Another TextFormField with a validator.
HARDReal project: onboarding, KYC, long sign-upExample 10 of 10

Multi-step registration

A step number in state decides which fields are visible. Next and Back change it, and the progress bar shows how far you are. Long forms feel short this way.
class Steps extends StatefulWidget {
  const Steps({super.key});
  @override
  State<Steps> createState() => _StepsState();
}
class _StepsState extends State<Steps> {
  int step = 0;
  final titles = ['Personal', 'Contact', 'Confirm'];
  @override
  Widget build(BuildContext context) {
    final pages = [
      const Column(children: [TextField(decoration: InputDecoration(labelText: 'Full name')), TextField(decoration: InputDecoration(labelText: 'Age'))]),
      const Column(children: [TextField(decoration: InputDecoration(labelText: 'Mobile')), TextField(decoration: InputDecoration(labelText: 'City'))]),
      const Center(child: Column(children: [Icon(Icons.check_circle, size: 70, color: Colors.green), Text('All set!', style: TextStyle(fontSize: 22))])),
    ];
    return Padding(padding: const EdgeInsets.fromLTRB(20, 50, 20, 20), child: Column(children: [
      Text('Step ${step + 1} of 3: ${titles[step]}', style: const TextStyle(fontSize: 20)),
      const SizedBox(height: 8),
      LinearProgressIndicator(value: (step + 1) / 3),
      const SizedBox(height: 20),
      pages[step],
      const Spacer(),
      Row(children: [
        if (step > 0) OutlinedButton(onPressed: () => setState(() => step--), child: const Text('Back')),
        const Spacer(),
        if (step < 2) ElevatedButton(onPressed: () => setState(() => step++), child: const Text('Next')),
      ]),
    ]));
  }
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Steps())));
Try it yourself: Add a fourth step "Documents".
Add to titles, pages and change 2 and 3.

Quick quiz

3 questions. Click an answer.
How do you read what the user typed in a TextField?
controller.textcontroller.sizeText.valuebuild()
What does a validator return when the value is OK?
trueAn empty stringnullfalse
Which widget lets the user pick exactly one option from a group?
CheckboxSwitchRadioSlider
Score: 0 / 3

Recap: what you learned in Module 10

TextField

controller.text and onChanged.

Choices

Checkbox, Switch, Radio, Dropdown keep a value in state.

Form

GlobalKey + validate() for checking input.

Validator

Return error text or null.

Slider/pickers

Safe numbers and dates.

Multi-step

A step number decides what is shown.

Next: Navigation: Many Screens, One App - Move between screens, dialogs and tabs
MODULE 11 · PART 3

Navigation: Many Screens, One App

Move between screens, dialogs and tabs
You will learn
  • Open and close screens with Navigator.push and pop
  • Send data to a screen and get a result back
  • Use named routes
  • Show dialogs, bottom sheets and snack bars
  • Build BottomNavigationBar, Drawer and TabBar apps
You will build: a list-detail-cart flow and a login-to-home app
4 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
🧭

Where is this used in real apps?

No real app has one screen. Login leads to Home, a product leads to details, details lead to the cart. Navigation connects them.

Navigator

Tap a product, a new page slides in; the back button returns.

Bottom bar / Drawer

Home, Search, Profile tabs; side menu with Settings and Log out.

Dialogs

"Delete this item?" confirmation before something important.

Home
🛒
Products
See all items
📦
My orders
3 active
👤
Profile
Edit details
+
🏠
Home
🔍
Search
👤
Me

The screen stack

Flutter keeps screens in a stack, like plates. push puts a new screen on top. pop removes the top one and shows the one below.

Navigator.push

Open a new screen on top of the current one.

Navigator.pop

Close the current screen and go back.

Back button

On Android the phone back button pops automatically.

Think of plates: you can only see and use the top plate.

push and pop in code

MaterialPageRoute describes the new screen and gives it the standard slide animation. Every Scaffold with an AppBar also gets a free back arrow.

context tells Navigator which screen we are on. Always pass the context you got in build().
// open the details screen
ElevatedButton(
  onPressed: () {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => const DetailsPage()),
    );
  },
  child: const Text('Open details'),
)

// on the details screen: go back
ElevatedButton(
  onPressed: () => Navigator.pop(context),
  child: const Text('Back'),
)

Sending data and getting a result

To send data, give the new screen constructor arguments. To get data back, await the push and send the value with pop(context, value).

Real use: a "Select city" screen that returns the chosen city to the form.
// send data: put it in the constructor
Navigator.push(context, MaterialPageRoute(
  builder: (_) => DetailsPage(name: 'Litti Chokha', price: 120),
));

// get a result back
final ok = await Navigator.push<bool>(context,
  MaterialPageRoute(builder: (_) => const ConfirmPage()));

// in ConfirmPage:
Navigator.pop(context, true);   // sends true back

Named routes

A routes table gives every screen a name like a web address. Easier to read and change in big apps.

Tip: pushReplacementNamed replaces the current screen, so back does not return to login.
MaterialApp(
  initialRoute: '/',
  routes: {
    '/': (context) => const HomePage(),
    '/cart': (context) => const CartPage(),
    '/profile': (context) => const ProfilePage(),
  },
)

// anywhere in the app
Navigator.pushNamed(context, '/cart');

Dialog, SnackBar, BottomSheet

These are not new screens but overlays. They sit above the page and are closed with Navigator.pop.

Use: dialog = ask, snackbar = inform, bottom sheet = choose.
// dialog
showDialog(context: context, builder: (_) => AlertDialog(
  title: const Text('Delete?'),
  actions: [TextButton(onPressed: () => Navigator.pop(context), child: const Text('No'))],
));

// snack bar (small message at the bottom)
ScaffoldMessenger.of(context).showSnackBar(
  const SnackBar(content: Text('Saved')));

// bottom sheet
showModalBottomSheet(context: context, builder: (_) => const SizedBox(height: 200));

BottomNavigationBar, Drawer, TabBar

BottomNavigationBar

3 to 5 main sections. Keep the selected index in state and show the matching page.

Drawer

A side menu opened by the hamburger icon. Good for many rarely used items.

TabBar + TabBarView

Swipeable tabs inside one screen: Chats, Status, Calls.

Choose

Bottom bar for the main areas; Drawer for extras like Settings and Help.

Rule: never put more than 5 items in a bottom bar.

Animated explainer: The navigation stack

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

Animated explainer: Passing data between screens

Press Next to walk through it step by step, or Auto play.
EASYReal project: open any second screenExample 1 of 10

push and pop

Two screens. The first pushes the second, the second pops itself. The AppBar back arrow also works.
class Home extends StatelessWidget {
  const Home({super.key});
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Home')),
    body: Center(child: ElevatedButton(
      child: const Text('Open About'),
      onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (_) => const About())),
    )),
  );
}
class About extends StatelessWidget {
  const About({super.key});
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('About')),
    body: Center(child: ElevatedButton(onPressed: () => Navigator.pop(context), child: const Text('Go back'))),
  );
}
void main() => runApp(const MaterialApp(home: Home()));
Try it yourself: Change the About title to "BrainBit Infotech".
AppBar(title: const Text('BrainBit Infotech'))
EASYReal project: product list to product detailsExample 2 of 10

Passing data to a screen

The details screen gets its data through constructor arguments. One DetailsPage can show any product.
class Details extends StatelessWidget {
  final String name; final int price;
  const Details({super.key, required this.name, required this.price});
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: Text(name)),
    body: Center(child: Text('Rs $price', style: const TextStyle(fontSize: 40))),
  );
}
class Home extends StatelessWidget {
  const Home({super.key});
  @override
  Widget build(BuildContext context) {
    final items = {'Litti Chokha': 120, 'Dhuska': 60, 'Lassi': 40};
    return Scaffold(
      appBar: AppBar(title: const Text('Menu')),
      body: ListView(children: items.entries.map((e) => ListTile(
        title: Text(e.key), trailing: const Icon(Icons.chevron_right),
        onTap: () => Navigator.push(context, MaterialPageRoute(builder: (_) => Details(name: e.key, price: e.value))),
      )).toList()),
    );
  }
}
void main() => runApp(const MaterialApp(home: Home()));
Try it yourself: Add "Jalebi": 30.
Add the pair to items.
EASYReal project: select city / pick option screensExample 3 of 10

Return a result

await Navigator.push waits until the other screen closes. pop(context, value) sends the answer back.
class Pick extends StatelessWidget {
  const Pick({super.key});
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Select city')),
    body: ListView(children: ['Ranchi', 'Patna', 'Jamshedpur'].map((c) => ListTile(
      title: Text(c), onTap: () => Navigator.pop(context, c))).toList()),
  );
}
class Home extends StatefulWidget {
  const Home({super.key});
  @override
  State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
  String city = 'No city chosen';
  @override
  Widget build(BuildContext context) => Scaffold(
    body: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
      Text(city, style: const TextStyle(fontSize: 24)),
      ElevatedButton(onPressed: () async {
        final r = await Navigator.push<String>(context, MaterialPageRoute(builder: (_) => const Pick()));
        if (r != null) setState(() => city = r);
      }, child: const Text('Choose city')),
    ])),
  );
}
void main() => runApp(const MaterialApp(home: Home()));
Try it yourself: Add "Dhanbad" to the cities.
Add to the list.
EASYReal project: bigger apps with many screensExample 4 of 10

Named routes

Routes get names in one table. Screens open with pushNamed, so nobody needs to import every page class.
class Page extends StatelessWidget {
  final String title; final String next;
  const Page(this.title, this.next, {super.key});
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: Text(title)),
    body: Center(child: ElevatedButton(onPressed: () => Navigator.pushNamed(context, next), child: Text('Go to $next'))),
  );
}
void main() {
  runApp(MaterialApp(
    initialRoute: '/',
    routes: {
      '/': (c) => const Page('Home', '/cart'),
      '/cart': (c) => const Page('Cart', '/profile'),
      '/profile': (c) => const Page('Profile', '/'),
    },
  ));
}
Try it yourself: Add a "/settings" page.
Add a route and make one page point to it.
EASYReal project: delete confirmationExample 5 of 10

AlertDialog and SnackBar

showDialog asks before something risky. After "Yes" a SnackBar confirms. Every serious app asks before deleting.
class Home extends StatelessWidget {
  const Home({super.key});
  @override
  Widget build(BuildContext context) => Scaffold(
    body: Center(child: ElevatedButton(
      child: const Text('Delete account'),
      onPressed: () => showDialog(context: context, builder: (ctx) => AlertDialog(
        title: const Text('Delete account?'),
        content: const Text('This cannot be undone.'),
        actions: [
          TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('No')),
          TextButton(onPressed: () {
            Navigator.pop(ctx);
            ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Account deleted')));
          }, child: const Text('Yes')),
        ],
      )),
    )),
  );
}
void main() => runApp(const MaterialApp(home: Home()));
Try it yourself: Change the question to "Log out?".
Edit the title Text and the button text.
MEDIUMReal project: main sections of an appExample 6 of 10

BottomNavigationBar

The selected index is state. The body shows pages[index]. Tapping a tab calls setState with the new index.
class Shell extends StatefulWidget {
  const Shell({super.key});
  @override
  State<Shell> createState() => _ShellState();
}
class _ShellState extends State<Shell> {
  int i = 0;
  final pages = const [Center(child: Text('Home page')), Center(child: Text('Search page')), Center(child: Text('Profile page'))];
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Ranchi Mart')),
    body: pages[i],
    bottomNavigationBar: BottomNavigationBar(
      currentIndex: i,
      onTap: (v) => setState(() => i = v),
      items: const [
        BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
        BottomNavigationBarItem(icon: Icon(Icons.search), label: 'Search'),
        BottomNavigationBarItem(icon: Icon(Icons.person), label: 'Profile'),
      ],
    ),
  );
}
void main() => runApp(const MaterialApp(home: Shell()));
Try it yourself: Add a "Cart" tab with Icons.shopping_cart.
Add a page and a BottomNavigationBarItem.
MEDIUMReal project: side menu with account and settingsExample 7 of 10

Drawer menu

A Drawer slides from the left. A DrawerHeader shows the user and ListTiles are the menu. Tapping one closes the drawer with pop.
class Home extends StatefulWidget {
  const Home({super.key});
  @override
  State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
  String page = 'Dashboard';
  Widget item(IconData i, String t) => ListTile(leading: Icon(i), title: Text(t),
    onTap: () { setState(() => page = t); Navigator.pop(context); });
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: Text(page)),
    drawer: Drawer(child: ListView(children: [
      const DrawerHeader(decoration: BoxDecoration(color: Colors.indigo),
        child: Text('Nandan Kumar\nBrainBit Infotech, Ranchi', style: TextStyle(color: Colors.white, fontSize: 20))),
      item(Icons.dashboard, 'Dashboard'), item(Icons.school, 'Courses'), item(Icons.settings, 'Settings'),
    ])),
    body: Center(child: Text('$page screen', style: const TextStyle(fontSize: 26))),
  );
}
void main() => runApp(const MaterialApp(home: Home()));
Try it yourself: Add a "Help" item.
item(Icons.help, 'Help'),
MEDIUMReal project: Chats / Status / Calls style tabsExample 8 of 10

TabBar with swipe

DefaultTabController connects a TabBar and a TabBarView. Tap a tab or swipe and both stay in sync.
void main() {
  runApp(MaterialApp(home: DefaultTabController(
    length: 3,
    child: Scaffold(
      appBar: AppBar(
        title: const Text('Class Group'),
        bottom: const TabBar(tabs: [Tab(text: 'Chats'), Tab(text: 'Status'), Tab(text: 'Calls')]),
      ),
      body: const TabBarView(children: [
        Center(child: Text('Chats list')),
        Center(child: Text('Status updates')),
        Center(child: Text('Call history')),
      ]),
    ),
  )));
}
Try it yourself: Add a fourth tab "Groups".
Change length to 4; add a Tab and a page.
HARDReal project: shopping flow in any store appExample 9 of 10

List, detail and cart

A list of products, a details page with "Add to cart" that returns a result, and a cart counter in the AppBar on the first screen. Three screens working together.
class Detail extends StatelessWidget {
  final String name;
  const Detail(this.name, {super.key});
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: Text(name)),
    body: Center(child: ElevatedButton(onPressed: () => Navigator.pop(context, name), child: const Text('Add to cart'))),
  );
}
class Shop extends StatefulWidget {
  const Shop({super.key});
  @override
  State<Shop> createState() => _ShopState();
}
class _ShopState extends State<Shop> {
  final cart = <String>[];
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: Text('Shop (cart: ${cart.length})'), actions: [
      IconButton(icon: const Icon(Icons.shopping_cart), onPressed: () => showDialog(context: context,
        builder: (_) => AlertDialog(title: const Text('Your cart'), content: Text(cart.isEmpty ? 'Empty' : cart.join(', '))))),
    ]),
    body: ListView(children: ['School Bag', 'Water Bottle', 'Notebook Set'].map((n) => ListTile(
      title: Text(n), trailing: const Icon(Icons.chevron_right),
      onTap: () async {
        final r = await Navigator.push<String>(context, MaterialPageRoute(builder: (_) => Detail(n)));
        if (r != null) setState(() => cart.add(r));
      },
    )).toList()),
  );
}
void main() => runApp(const MaterialApp(home: Shop()));
Try it yourself: Show a SnackBar "Added to cart" after returning.
ScaffoldMessenger.of(context).showSnackBar(...) after setState.
HARDReal project: every app with loginExample 10 of 10

Login to Home flow

After a successful login pushReplacement swaps Login for Home, so the back button no longer returns to Login. Logout replaces it again. This is the start of every real app.
class Login extends StatefulWidget {
  const Login({super.key});
  @override
  State<Login> createState() => _LoginState();
}
class _LoginState extends State<Login> {
  final user = TextEditingController();
  final pass = TextEditingController();
  String err = '';
  @override
  Widget build(BuildContext context) => Scaffold(
    body: Padding(padding: const EdgeInsets.all(24), child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
      const Text('Welcome', style: TextStyle(fontSize: 30)),
      TextField(controller: user, decoration: const InputDecoration(labelText: 'User (try: ranchi)')),
      TextField(controller: pass, obscureText: true, decoration: const InputDecoration(labelText: 'Password (try: 1234)')),
      const SizedBox(height: 12),
      ElevatedButton(onPressed: () {
        if (user.text == 'ranchi' && pass.text == '1234') {
          Navigator.pushReplacement(context, MaterialPageRoute(builder: (_) => Home(user.text)));
        } else { setState(() => err = 'Wrong user or password'); }
      }, child: const Text('Login')),
      Text(err, style: const TextStyle(color: Colors.red)),
    ])),
  );
}
class Home extends StatelessWidget {
  final String user;
  const Home(this.user, {super.key});
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Home'), automaticallyImplyLeading: false, actions: [
      IconButton(icon: const Icon(Icons.logout), onPressed: () => Navigator.pushReplacement(context, MaterialPageRoute(builder: (_) => const Login()))),
    ]),
    body: Center(child: Text('Hello, $user!', style: const TextStyle(fontSize: 28))),
  );
}
void main() => runApp(const MaterialApp(home: Login()));
Try it yourself: Also accept user "patna" with password "5678".
Add an || condition for the second pair.

Quick quiz

3 questions. Click an answer.
Which call opens a new screen on top of the current one?
Navigator.popNavigator.pushrunAppsetState
How does a screen send data back to the previous one?
pop(context, value)push(value)build(value)It cannot
Where do you keep the selected tab number of a BottomNavigationBar?
In stateIn pubspec.yamlIn an IconNowhere
Score: 0 / 3

Recap: what you learned in Module 11

Stack

push adds a screen, pop removes it.

Data in

Constructor arguments.

Data out

await push, pop(context, value).

Routes

Named routes in MaterialApp.

Overlays

Dialog, SnackBar, BottomSheet.

Structure

BottomNavigationBar, Drawer, TabBar.

Next: Animations, Themes and Responsive UI - Make the app beautiful and alive
MODULE 12 · PART 3

Animations, Themes and Responsive UI

Make the app beautiful and alive
You will learn
  • Animate with AnimatedContainer and AnimatedOpacity
  • Switch widgets smoothly with AnimatedSwitcher
  • Control animation with AnimationController
  • Set light and dark themes for the whole app
  • Fit any screen with MediaQuery and LayoutBuilder
You will build: an animated onboarding and a progress card
4 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
✨

Where is this used in real apps?

Small animations make apps feel premium: a heart that pops, a card that expands, a dark mode that changes everything at once.

Implicit animations

Change a value and Flutter animates it for you: size, colour, opacity.

Theme

Change one colour in one place and the whole app follows.

Responsive

The same app looks right on a small phone, a big phone and a tablet.

Themes
☀
Light mode
Default
🌙
Dark mode
Night reading
🎨
Brand colour
BrainBit Infotech blue

Implicit animations

Put a duration and change a value in setState. The widget glides from the old value to the new one. You write no animation code at all.

Family: AnimatedContainer, AnimatedOpacity, AnimatedPadding, AnimatedAlign, AnimatedPositioned, AnimatedCrossFade.
AnimatedContainer(
  duration: const Duration(milliseconds: 500),
  curve: Curves.easeInOut,
  width: big ? 200 : 100,
  height: big ? 200 : 100,
  decoration: BoxDecoration(
    color: big ? Colors.orange : Colors.blue,
    borderRadius: BorderRadius.circular(big ? 100 : 8),
  ),
)

AnimatedOpacity and AnimatedSwitcher

AnimatedOpacity

opacity: show ? 1 : 0 fades a widget in and out.

AnimatedSwitcher

When its child changes, the old one fades out and the new one fades in. Give the child a different key.

AnimatedCrossFade

Fades between exactly two children, for example show more / show less.

Curves

easeIn, easeOut, bounceOut, elasticOut change how the motion feels.

Real use: counter number that fades to the next number, loading spinner that turns into a tick.

AnimationController: full control

An AnimationController counts from 0 to 1 over a duration. AnimatedBuilder redraws a widget on every tick. Use it for repeating or multi-step animations.

Always dispose a controller in dispose(), or it keeps running after the screen is closed.
class _PulseState extends State<Pulse> with SingleTickerProviderStateMixin {
  late AnimationController c;

  @override
  void initState() {
    super.initState();
    c = AnimationController(vsync: this, duration: const Duration(seconds: 1))
      ..repeat(reverse: true);
  }

  @override
  void dispose() { c.dispose(); super.dispose(); }

  @override
  Widget build(BuildContext context) => AnimatedBuilder(
    animation: c,
    builder: (context, child) => Container(
      width: 60 + c.value * 60, height: 60 + c.value * 60,
      decoration: const BoxDecoration(color: Colors.red, shape: BoxShape.circle),
    ),
  );
}

Theme: one place for the look

ThemeData sets colours, fonts and shapes for every widget. colorSchemeSeed builds a full matching palette from one colour. darkTheme + themeMode give dark mode.

Rule: never hard-code the same colour in 50 places. Put it in the Theme.
MaterialApp(
  theme: ThemeData(
    colorSchemeSeed: Colors.indigo,
    useMaterial3: true,
    brightness: Brightness.light,
  ),
  darkTheme: ThemeData(
    colorSchemeSeed: Colors.indigo,
    brightness: Brightness.dark,
  ),
  themeMode: ThemeMode.system,     // or .light / .dark
  home: const HomePage(),
)

// read the theme anywhere
Theme.of(context).colorScheme.primary
Theme.of(context).textTheme.titleLarge

MediaQuery and LayoutBuilder

MediaQuery tells you about the whole screen. LayoutBuilder tells you the space your widget got. Use them to switch layouts: 1 column on a phone, 2 on a tablet.

Real use: product grid with 2 columns on phones and 4 on tablets.
// screen size and settings
final size = MediaQuery.of(context).size;
final isSmall = size.width < 360;
final top = MediaQuery.of(context).padding.top;   // status bar

// size of the parent box
LayoutBuilder(builder: (context, box) {
  if (box.maxWidth > 600) return const TabletLayout();
  return const PhoneLayout();
})

Animated explainer: How AnimatedContainer works

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

Animated explainer: Theme flows down the tree

Press Next to walk through it step by step, or Auto play.
EASYReal project: expanding cards, selected highlightsExample 1 of 10

AnimatedContainer

Tap the box: big flips, and AnimatedContainer glides to the new size, colour and corner. No animation code.
class Grow extends StatefulWidget {
  const Grow({super.key});
  @override
  State<Grow> createState() => _GrowState();
}
class _GrowState extends State<Grow> {
  bool big = false;
  @override
  Widget build(BuildContext context) {
    return Center(child: GestureDetector(
      onTap: () => setState(() => big = !big),
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 500),
        curve: Curves.easeInOut,
        width: big ? 220 : 100, height: big ? 220 : 100,
        decoration: BoxDecoration(color: big ? Colors.orange : Colors.indigo, borderRadius: BorderRadius.circular(big ? 110 : 12)),
        alignment: Alignment.center,
        child: Text(big ? 'Big' : 'Tap', style: const TextStyle(color: Colors.white, fontSize: 20)),
      ),
    ));
  }
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Grow())));
Try it yourself: Change the duration to 2 seconds.
Duration(seconds: 2)
EASYReal project: fade in a banner or hintExample 2 of 10

AnimatedOpacity fade

AnimatedOpacity fades a widget between 0 and 1. The button toggles the bool that drives it.
class Fade extends StatefulWidget {
  const Fade({super.key});
  @override
  State<Fade> createState() => _FadeState();
}
class _FadeState extends State<Fade> {
  bool show = true;
  @override
  Widget build(BuildContext context) {
    return Column(mainAxisAlignment: MainAxisAlignment.center, children: [
      AnimatedOpacity(
        opacity: show ? 1 : 0,
        duration: const Duration(milliseconds: 600),
        child: const Icon(Icons.wb_sunny, size: 100, color: Colors.orange),
      ),
      ElevatedButton(onPressed: () => setState(() => show = !show), child: Text(show ? 'Hide' : 'Show')),
    ]);
  }
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Fade())));
Try it yourself: Replace the sun with Icons.favorite in red.
Icon(Icons.favorite, color: Colors.red)
EASYReal project: theme switch in settingsExample 3 of 10

Light and dark theme

The themeMode lives in state of a top-level widget. The Switch flips it, and every widget changes colours at once.
class App extends StatefulWidget {
  const App({super.key});
  @override
  State<App> createState() => _AppState();
}
class _AppState extends State<App> {
  bool dark = false;
  @override
  Widget build(BuildContext context) => MaterialApp(
    theme: ThemeData(colorSchemeSeed: Colors.indigo),
    darkTheme: ThemeData(colorSchemeSeed: Colors.indigo, brightness: Brightness.dark),
    themeMode: dark ? ThemeMode.dark : ThemeMode.light,
    home: Scaffold(
      appBar: AppBar(title: const Text('Theme demo')),
      body: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
        const Text('Hello Ranchi', style: TextStyle(fontSize: 28)),
        Switch(value: dark, onChanged: (v) => setState(() => dark = v)),
        ElevatedButton(onPressed: () {}, child: const Text('A button')),
      ])),
    ),
  );
}
void main() => runApp(const App());
Try it yourself: Change colorSchemeSeed to Colors.teal in both themes.
Edit both ThemeData lines.
EASYReal project: sizes that fit every phoneExample 4 of 10

MediaQuery: screen size

MediaQuery.of(context).size gives the screen width and height. Here a box always takes 80 percent of the width.
class Info extends StatelessWidget {
  const Info({super.key});
  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return Scaffold(body: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
      Text('Width: ${size.width.toStringAsFixed(0)}  Height: ${size.height.toStringAsFixed(0)}'),
      const SizedBox(height: 16),
      Container(width: size.width * 0.8, height: 60, color: Colors.teal, alignment: Alignment.center,
          child: const Text('80% of width', style: TextStyle(color: Colors.white))),
    ])));
  }
}
void main() => runApp(const MaterialApp(home: Info()));
Try it yourself: Make the box 50 percent of the width.
size.width * 0.5
EASYReal project: premium-looking cards and bannersExample 5 of 10

Gradient and shadow

BoxDecoration can hold a gradient, rounded corners and a shadow together. This is how offer banners and cards get depth.
void main() {
  runApp(MaterialApp(home: Scaffold(body: Center(child: Container(
    width: 280, height: 150, padding: const EdgeInsets.all(20),
    decoration: BoxDecoration(
      gradient: const LinearGradient(colors: [Color(0xFF6A11CB), Color(0xFF2575FC)], begin: Alignment.topLeft, end: Alignment.bottomRight),
      borderRadius: BorderRadius.circular(20),
      boxShadow: const [BoxShadow(color: Colors.black38, blurRadius: 14, offset: Offset(0, 8))],
    ),
    child: const Column(crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
      Text('Festival Offer', style: TextStyle(color: Colors.white, fontSize: 24, fontWeight: FontWeight.bold)),
      Text('Up to 40% off on Ranchi Mart', style: TextStyle(color: Colors.white70)),
    ]),
  )))));
}
Try it yourself: Change the gradient colours to green and teal.
Color(0xFF11998E), Color(0xFF38EF7D)
MEDIUMReal project: responsive product gridExample 6 of 10

LayoutBuilder: phone or tablet

LayoutBuilder gives the width of the space available. More width means more grid columns. One code base fits phones and tablets.
void main() {
  runApp(MaterialApp(home: Scaffold(
    appBar: AppBar(title: const Text('Responsive grid')),
    body: LayoutBuilder(builder: (context, box) {
      final cols = box.maxWidth > 600 ? 4 : box.maxWidth > 300 ? 3 : 2;
      return Column(children: [
        Padding(padding: const EdgeInsets.all(8), child: Text('Width ${box.maxWidth.toStringAsFixed(0)} so $cols columns')),
        Expanded(child: GridView.count(crossAxisCount: cols, padding: const EdgeInsets.all(8), crossAxisSpacing: 8, mainAxisSpacing: 8,
          children: List.generate(8, (i) => Container(color: Colors.indigo.shade100, alignment: Alignment.center, child: Text('${i + 1}')))),
        ),
      ]);
    }),
  )));
}
Try it yourself: Make 3 columns start at width 200.
box.maxWidth > 200 ? 3
MEDIUMReal project: price or score that changesExample 7 of 10

AnimatedSwitcher counter

When the child changes, AnimatedSwitcher fades the old one out and the new one in. The key tells it the child is different.
class Count extends StatefulWidget {
  const Count({super.key});
  @override
  State<Count> createState() => _CountState();
}
class _CountState extends State<Count> {
  int n = 0;
  @override
  Widget build(BuildContext context) {
    return Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
      AnimatedSwitcher(
        duration: const Duration(milliseconds: 400),
        child: Text('$n', key: ValueKey(n), style: const TextStyle(fontSize: 90, fontWeight: FontWeight.bold, color: Colors.indigo)),
      ),
      ElevatedButton(onPressed: () => setState(() => n++), child: const Text('Add')),
    ]));
  }
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Count())));
Try it yourself: Make the number red when it is above 5.
color: n > 5 ? Colors.red : Colors.indigo
MEDIUMReal project: loading dot, live badge, heartbeatExample 8 of 10

AnimationController pulse

A controller repeats from 0 to 1 and back. AnimatedBuilder redraws a circle each tick, so it keeps pulsing. dispose() stops it.
class Pulse extends StatefulWidget {
  const Pulse({super.key});
  @override
  State<Pulse> createState() => _PulseState();
}
class _PulseState extends State<Pulse> with SingleTickerProviderStateMixin {
  late AnimationController c;
  @override
  void initState() {
    super.initState();
    c = AnimationController(vsync: this, duration: const Duration(milliseconds: 900))..repeat(reverse: true);
  }
  @override
  void dispose() { c.dispose(); super.dispose(); }
  @override
  Widget build(BuildContext context) => Center(child: AnimatedBuilder(
    animation: c,
    builder: (context, child) => Container(
      width: 60 + c.value * 70, height: 60 + c.value * 70, alignment: Alignment.center,
      decoration: BoxDecoration(color: Colors.red.withOpacity(0.4 + c.value * 0.6), shape: BoxShape.circle),
      child: const Icon(Icons.favorite, color: Colors.white),
    ),
  ));
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Pulse())));
Try it yourself: Change the colour to blue.
Colors.blue.withOpacity(...)
HARDReal project: first-run welcome screensExample 9 of 10

Animated onboarding

Three welcome pages. The dots under them are AnimatedContainers: the selected one grows wide. Next moves on and the last button says Start.
class Onboard extends StatefulWidget {
  const Onboard({super.key});
  @override
  State<Onboard> createState() => _OnboardState();
}
class _OnboardState extends State<Onboard> {
  int i = 0;
  final pages = [['\u{1F4DA}', 'Learn Flutter', 'Short lessons for every level'], ['\u{1F4F1}', 'Build apps', 'Practice with real projects'], ['\u{1F3C6}', 'Get certified', 'Show your skills to employers']];
  @override
  Widget build(BuildContext context) {
    return Padding(padding: const EdgeInsets.all(28), child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
      AnimatedSwitcher(
        duration: const Duration(milliseconds: 350),
        child: Column(key: ValueKey(i), children: [
          Text(pages[i][0], style: const TextStyle(fontSize: 90)),
          Text(pages[i][1], style: const TextStyle(fontSize: 26, fontWeight: FontWeight.bold)),
          Text(pages[i][2]),
        ]),
      ),
      const SizedBox(height: 30),
      Row(mainAxisAlignment: MainAxisAlignment.center, children: [
        for (var k = 0; k < 3; k++) AnimatedContainer(
          duration: const Duration(milliseconds: 300), margin: const EdgeInsets.all(4),
          width: k == i ? 28 : 10, height: 10,
          decoration: BoxDecoration(color: k == i ? Colors.indigo : Colors.grey.shade400, borderRadius: BorderRadius.circular(5)),
        ),
      ]),
      const SizedBox(height: 30),
      ElevatedButton(onPressed: () => setState(() => i = i < 2 ? i + 1 : 0), child: Text(i < 2 ? 'Next' : 'Start again')),
    ]));
  }
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Onboard())));
Try it yourself: Add a fourth page "Join BrainBit Infotech".
Add a list to pages and change 3 and 2 to 4 and 3.
HARDReal project: fee, course or goal progress cardExample 10 of 10

Animated progress card

A card whose bar and number animate to the new percent. TweenAnimationBuilder animates any number from the old value to the new one.
class Prog extends StatefulWidget {
  const Prog({super.key});
  @override
  State<Prog> createState() => _ProgState();
}
class _ProgState extends State<Prog> {
  double pct = 0.25;
  @override
  Widget build(BuildContext context) {
    return Center(child: Card(margin: const EdgeInsets.all(20), child: Padding(padding: const EdgeInsets.all(20), child: Column(mainAxisSize: MainAxisSize.min, children: [
      const Text('Flutter Course Progress', style: TextStyle(fontSize: 20)),
      const SizedBox(height: 16),
      TweenAnimationBuilder<double>(
        tween: Tween<double>(begin: 0, end: pct),
        duration: const Duration(milliseconds: 800),
        builder: (context, v, child) => Column(children: [
          LinearProgressIndicator(value: v, minHeight: 14),
          const SizedBox(height: 8),
          Text('${(v * 100).toStringAsFixed(0)}%', style: const TextStyle(fontSize: 32, color: Colors.indigo)),
        ]),
      ),
      const SizedBox(height: 12),
      Row(mainAxisAlignment: MainAxisAlignment.center, children: [
        OutlinedButton(onPressed: () => setState(() => pct = 0.25), child: const Text('25%')),
        const SizedBox(width: 8),
        OutlinedButton(onPressed: () => setState(() => pct = 0.6), child: const Text('60%')),
        const SizedBox(width: 8),
        ElevatedButton(onPressed: () => setState(() => pct = 1.0), child: const Text('100%')),
      ]),
    ]))));
  }
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Prog())));
Try it yourself: Add a button for 80%.
OutlinedButton(onPressed: () => setState(() => pct = 0.8), ...)

Quick quiz

3 questions. Click an answer.
What do you need to add to animate an AnimatedContainer?
A duration and a changed valueA controllerA StackA Future
Where should an AnimationController be disposed?
build()dispose()main()Never
Which gives you the width of the whole screen?
MediaQueryPaddingChipDivider
Score: 0 / 3

Recap: what you learned in Module 12

Implicit

Animated* widgets glide between values.

Switcher

Fades between different children using keys.

Controller

Full control; always dispose.

Theme

One place for colours and fonts, plus dark mode.

MediaQuery

Whole-screen size and settings.

LayoutBuilder

Space the parent gives; switch layouts.

Next: the next part of the course.

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