COMPLETE FLUTTER COURSE · BRAINBIT INFOTECH

Part 2

4 modules · 16 class hours · 40 practical examples

Module 5: Your First Real Widgets

StatelessWidget, Text, Container, Scaffold, Icon, Image and Theme · 4 h

Module 6: Layouts: Row, Column, Stack

Place widgets exactly where you want them · 4 h

Module 7: UI Components: Buttons, Cards, Chips

The ready-made parts every app is built from · 4 h

Module 8: Lists, Grids and Scrolling

Show 10 or 10,000 items with the same code · 4 h

MODULE 5 · PART 2

Your First Real Widgets

StatelessWidget, Text, Container, Scaffold, Icon, Image and Theme
You will learn
  • Create your own widget with StatelessWidget
  • Style text, boxes, icons and images
  • Use Scaffold to build a full page
  • Reuse one widget many times
  • Colour the whole app with one Theme
You will build: a course card, a notice board and a login screen layout
4 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
🧱

Where is this used in real apps?

Every screen you have ever used is built from the same few widgets. Learn these well and you can build almost any screen.

Text + Container = cards

Course cards, price tags, notice boards: a styled box with text inside.

Scaffold = page frame

Top bar, body, floating button and drawer all come ready from Scaffold.

Your own widgets

A ProductCard widget written once is used on 20 screens. Less code, fewer bugs.

Courses
📱
Flutter
80 hrs
🐍
Python
60 hrs
🌐
Web Design
40 hrs
📊
Excel
30 hrs

StatelessWidget: your own widget

A StatelessWidget is a widget that never changes by itself: you give it data, it draws it. You write a class with a build() method that returns other widgets.

Read it: "MyApp is a StatelessWidget. When Flutter calls build(), it gets a MaterialApp."
void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: Scaffold(
        body: Center(
          child: Text('This is my own widget!'),
        ),
      ),
    );
  }
}

Text and TextStyle

TextStyle controls size, weight, colour, spacing and decoration. One Text can have only one style.
void main() {
  runApp(const MaterialApp(
    home: Scaffold(
      body: Padding(
        padding: EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('Big and bold',
                style: TextStyle(fontSize: 30,
                    fontWeight: FontWeight.bold)),
            Text('Coloured italic',
                style: TextStyle(color: Colors.teal,
                    fontStyle: FontStyle.italic, fontSize: 22)),
            Text('Spaced letters',
                style: TextStyle(letterSpacing: 4, fontSize: 20)),
            Text('Underlined',
                style: TextStyle(
                    decoration: TextDecoration.underline,
                    fontSize: 22)),
          ],
        ),
      ),
    ),
  ));
}

Container: the all-rounder box

Size and space

width, height, padding (inside), margin (outside).

Look

color or decoration: BoxDecoration(...) for gradient, border, radius, shadow.

Shape

BoxShape.circle makes a round box; borderRadius rounds the corners.

Alignment

alignment: Alignment.center puts the child in a chosen spot.

Rule: use color OR decoration, not both. Put the colour inside BoxDecoration when you use it.

Scaffold: the page skeleton

appBar

Top bar with title and action icons.

body

The main content of the page.

floatingActionButton

The round main-action button.

drawer / bottomNavigationBar

Side menu and bottom tabs (Module 11).

One Scaffold per screen. It also gives SnackBars and drawers a place to appear.

Icon, Image and CircleAvatar

On a real phone Image.network loads the picture from the internet. In these slides a coloured placeholder is drawn instead.
void main() {
  runApp(MaterialApp(
    home: Scaffold(
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Icon(Icons.favorite, color: Colors.red, size: 48),
            const SizedBox(height: 12),
            const CircleAvatar(
              radius: 36,
              backgroundColor: Colors.indigo,
              child: Text('AK', style: TextStyle(fontSize: 24, color: Colors.white)),
            ),
            const SizedBox(height: 12),
            ClipRRect(
              borderRadius: BorderRadius.circular(16),
              child: Image.network('https://example.com/ranchi.jpg',
                  width: 200, height: 110, fit: BoxFit.cover),
            ),
          ],
        ),
      ),
    ),
  ));
}

Reusable widgets: write once, use everywhere

Our own widget takes data in its constructor (title, hours) and draws it. Change the design once in CourseTile and every tile in the app changes.

Golden rule of Flutter: when you copy-paste the same widgets twice, make your own widget instead.
class CourseTile extends StatelessWidget {
  final String title;
  final int hours;
  const CourseTile({super.key, required this.title, required this.hours});

  @override
  Widget build(BuildContext context) {
    return ListTile(
      leading: const Icon(Icons.school),
      title: Text(title),
      subtitle: Text('$hours hours'),
    );
  }
}

// use it as many times as you like
Column(children: const [
  CourseTile(title: 'Flutter', hours: 80),
  CourseTile(title: 'Python', hours: 60),
])

Theme: colour the whole app once

Instead of colouring every widget by hand, set a Theme once. Buttons, the AppBar, switches and sliders all pick up the colour. Theme.of(context) reads it anywhere.

Real use: to rebrand an app for a client, change one line (the seed colour).
MaterialApp(
  theme: ThemeData(
    colorSchemeSeed: Colors.teal,   // one colour makes a full palette
    useMaterial3: true,
  ),
  home: const HomePage(),
)

// anywhere below, read the theme:
Text('Hello',
  style: TextStyle(
    color: Theme.of(context).colorScheme.primary,
  ),
)

const: small habit, big benefit

What

const tells Flutter "this widget never changes".

Why

Flutter builds it once and reuses it, so the app runs faster and uses less battery.

When

Put const in front of widgets whose values are fixed: const Text('Hi').

Helper

The editor underlines places where const can be added. Press Ctrl+. and accept.

Cannot use const? If a value comes from a variable (like $name), the widget is not constant. That is normal.

Animated explainer: What build() does

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

Animated explainer: Container, layer by layer

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

Animated explainer: Reusing one widget

Press Next to walk through it step by step, or Auto play.
EASYReal project: root widget of every Flutter appExample 1 of 10

MyApp: your own widget

Almost every Flutter app starts with a StatelessWidget called MyApp whose build() returns MaterialApp. This is the template you will use for every project.
void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: Text('My first StatelessWidget',
              style: TextStyle(fontSize: 24)),
        ),
      ),
    );
  }
}
Try it yourself: Rename the class to RanchiApp (change it in both places).
The name appears in runApp(...) and in class ... extends.
EASYReal project: headings and labels of every screenExample 2 of 10

Text styling

Different TextStyle options make a heading, a label and a note look different. maxLines + overflow cut very long text with "...".
void main() {
  runApp(const MaterialApp(
    home: Scaffold(
      body: Padding(
        padding: EdgeInsets.all(20),
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          Text('Ranchi Mart', style: TextStyle(fontSize: 34, fontWeight: FontWeight.bold)),
          Text('Fresh groceries, fast', style: TextStyle(fontSize: 18, color: Colors.green, fontStyle: FontStyle.italic)),
          SizedBox(height: 14),
          Text('OFFER', style: TextStyle(letterSpacing: 6, fontSize: 20)),
          Text('Old price', style: TextStyle(decoration: TextDecoration.lineThrough, color: Colors.grey)),
          SizedBox(height: 14),
          Text('This is a very long description of the product that will not fit in one line on a small phone screen.',
              maxLines: 2, overflow: TextOverflow.ellipsis),
        ]),
      ),
    ),
  ));
}
Try it yourself: Make the title red and change maxLines to 1.
color: Colors.red inside the first TextStyle; maxLines: 1.
EASYReal project: price tags, badges, avatar framesExample 3 of 10

Container decoration

BoxDecoration gives a Container gradient, round corners, border and shadow. Here are three boxes: a gradient card, a circle and a bordered tag.
void main() {
  runApp(MaterialApp(
    home: Scaffold(
      body: Center(
        child: Column(mainAxisSize: MainAxisSize.min, children: [
          Container(
            width: 240, height: 90, alignment: Alignment.center,
            decoration: BoxDecoration(
              gradient: const LinearGradient(colors: [Colors.orange, Colors.pink]),
              borderRadius: BorderRadius.circular(16)),
            child: const Text('50% OFF', style: TextStyle(color: Colors.white, fontSize: 28)),
          ),
          const SizedBox(height: 16),
          Container(
            width: 90, height: 90,
            decoration: const BoxDecoration(color: Colors.teal, shape: BoxShape.circle),
            child: const Icon(Icons.shopping_bag, color: Colors.white, size: 44),
          ),
          const SizedBox(height: 16),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
            decoration: BoxDecoration(border: Border.all(color: Colors.green, width: 2), borderRadius: BorderRadius.circular(20)),
            child: const Text('In stock'),
          ),
        ]),
      ),
    ),
  ));
}
Try it yourself: Change the gradient to blue and purple and make the circle square (remove the shape).
colors: [Colors.blue, Colors.purple]; delete shape: BoxShape.circle.
EASYReal project: home screen of a shop or school appExample 4 of 10

Scaffold with AppBar actions

Scaffold gives each part a place: appBar with title and action icons, body, and a floatingActionButton.
void main() {
  runApp(MaterialApp(
    home: Scaffold(
      backgroundColor: Colors.grey.shade100,
      appBar: AppBar(
        title: const Text('Ranchi Mart'),
        actions: [
          IconButton(icon: const Icon(Icons.search), onPressed: () {}),
          IconButton(icon: const Icon(Icons.shopping_cart), onPressed: () {}),
        ],
      ),
      body: const Center(child: Text('Products will come here')),
      floatingActionButton: FloatingActionButton(
        onPressed: () {},
        child: const Icon(Icons.add),
      ),
    ),
  ));
}
Try it yourself: Add a third action icon for notifications (Icons.notifications).
Copy one IconButton line and change the icon name.
EASYReal project: profile card with photoExample 5 of 10

Icons, avatar and image

Icon draws a symbol, CircleAvatar a round profile picture (or initials), Image.network a picture from the internet. ClipRRect rounds its corners.
void main() {
  runApp(const MaterialApp(
    home: Scaffold(
      body: Center(
        child: Column(mainAxisSize: MainAxisSize.min, children: [
          ClipRRect(
            borderRadius: BorderRadius.all(Radius.circular(16)),
            child: Image.network('https://example.com/ranchi-falls.jpg', width: 260, height: 130, fit: BoxFit.cover),
          ),
          SizedBox(height: 14),
          CircleAvatar(radius: 34, backgroundColor: Colors.deepPurple,
              child: Text('NK', style: TextStyle(fontSize: 22, color: Colors.white))),
          SizedBox(height: 8),
          Text('Nandan Kumar', style: TextStyle(fontSize: 22)),
          Row(mainAxisSize: MainAxisSize.min, children: [Icon(Icons.location_on, color: Colors.red), Text('Ranchi')]),
        ]),
      ),
    ),
  ));
}
Try it yourself: Use your own initials in the avatar and change its colour.
Edit Text('NK') and backgroundColor.
MEDIUMReal project: course / product card in a catalogueExample 6 of 10

A course card

We combine Container, Row, Column, Icon and Text into one polished card. This one card is the building block of catalogue screens.
void main() {
  runApp(MaterialApp(
    home: Scaffold(
      backgroundColor: Colors.blue.shade50,
      body: Center(
        child: Container(
          width: 320, padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(16),
              boxShadow: const [BoxShadow(color: Colors.black12, blurRadius: 10)]),
          child: Row(children: [
            Container(
              width: 64, height: 64,
              decoration: BoxDecoration(color: Colors.blue.shade100, borderRadius: BorderRadius.circular(14)),
              child: const Icon(Icons.phone_android, size: 36, color: Colors.blue),
            ),
            const SizedBox(width: 14),
            const Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
              Text('Flutter App Development', style: TextStyle(fontSize: 17, fontWeight: FontWeight.bold)),
              Text('80 hours - Ranchi'),
              Text('Rs 14,999', style: TextStyle(color: Colors.green)),
            ]),
          ]),
        ),
      ),
    ),
  ));
}
Try it yourself: Change the icon to Icons.code and the colours to orange.
Icons.code; Colors.orange.shade100; Colors.orange.
MEDIUMReal project: product list item used across the appExample 7 of 10

Reusable CourseTile widget

The same card is needed for every course. We write CourseTile as our own widget with a constructor (title, hours, fee) and use it three times.
class CourseTile extends StatelessWidget {
  final String title;
  final int hours, fee;
  final IconData icon;
  const CourseTile({super.key, required this.title, required this.hours, required this.fee, required this.icon});

  @override
  Widget build(BuildContext context) {
    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
      child: ListTile(leading: Icon(icon, size: 34, color: Colors.indigo),
          title: Text(title), subtitle: Text('$hours hours'), trailing: Text('Rs $fee')),
    );
  }
}

void main() {
  runApp(const MaterialApp(
    home: Scaffold(
      body: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
        CourseTile(title: 'Flutter', hours: 80, fee: 14999, icon: Icons.phone_android),
        CourseTile(title: 'Python', hours: 60, fee: 9999, icon: Icons.code),
        CourseTile(title: 'Excel', hours: 30, fee: 3999, icon: Icons.table_chart),
      ]),
    ),
  ));
}
Try it yourself: Add a fourth tile for "Web Design", 40 hours, Rs 6999.
Copy one CourseTile(...) line and change the values.
MEDIUMReal project: brand colours of a client's appExample 8 of 10

ThemeData for the whole app

One colorSchemeSeed colours the AppBar, buttons, switches and more. Change the seed and the whole app changes. Theme.of(context) reads the colours in your own widgets.
void main() {
  runApp(MaterialApp(
    theme: ThemeData(colorSchemeSeed: Colors.teal, useMaterial3: true),
    home: const Home(),
  ));
}

class Home extends StatelessWidget {
  const Home({super.key});
  @override
  Widget build(BuildContext context) {
    final colors = Theme.of(context).colorScheme;
    return Scaffold(
      appBar: AppBar(title: const Text('Themed app'), backgroundColor: colors.primaryContainer),
      body: Center(
        child: Column(mainAxisSize: MainAxisSize.min, children: [
          Text('Primary colour text', style: TextStyle(fontSize: 22, color: colors.primary)),
          const SizedBox(height: 12),
          ElevatedButton(onPressed: () {}, child: const Text('Themed button')),
          const SizedBox(height: 12),
          Icon(Icons.verified, size: 48, color: colors.primary),
        ]),
      ),
    );
  }
}
Try it yourself: Change the seed to Colors.deepOrange and see everything change.
colorSchemeSeed: Colors.deepOrange
HARDReal project: notice board / announcements screen of a school appExample 9 of 10

School notice board

A list of notices built from data: each notice has a colour, icon, title and date. We loop over the data and produce one reusable NoticeCard per item (map(...).toList()). Add a notice to the list and it appears.
class Notice {
  final String title, date;
  final IconData icon;
  final Color color;
  const Notice(this.title, this.date, this.icon, this.color);
}

class NoticeCard extends StatelessWidget {
  final Notice n;
  const NoticeCard(this.n, {super.key});
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.fromLTRB(14, 8, 14, 0), padding: const EdgeInsets.all(14),
      decoration: BoxDecoration(color: n.color.withOpacity(0.12), borderRadius: BorderRadius.circular(14),
          border: Border(left: BorderSide(color: n.color, width: 6))),
      child: Row(children: [
        Icon(n.icon, color: n.color, size: 32), const SizedBox(width: 12),
        Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          Text(n.title, style: const TextStyle(fontSize: 17, fontWeight: FontWeight.bold)),
          Text(n.date),
        ]),
      ]),
    );
  }
}

void main() {
  const notices = [
    Notice('Annual Day on 14 Dec', '10 Nov 2026', Icons.celebration, Colors.purple),
    Notice('Fee last date 30 Nov', '08 Nov 2026', Icons.payments, Colors.red),
    Notice('Chhath holiday', '05 Nov 2026', Icons.event_busy, Colors.orange),
    Notice('PTM this Saturday', '02 Nov 2026', Icons.groups, Colors.teal),
  ];
  runApp(MaterialApp(home: Scaffold(
    appBar: AppBar(title: const Text('DAV Notice Board')),
    body: Column(children: notices.map((n) => NoticeCard(n)).toList()),
  )));
}
Try it yourself: Add a fifth notice: "Science exhibition", Icons.science, Colors.blue.
Add Notice(...) inside the notices list.
HARDReal project: login / sign-in screen of any appExample 10 of 10

Login screen layout

A real login screen layout: logo, title, two input-style boxes, a button and a link. A small helper function field() builds each box. In Module 10 we make the boxes work.
Widget field(String t) => Container(
  padding: const EdgeInsets.all(14),
  decoration: BoxDecoration(border: Border.all(color: Colors.grey), borderRadius: BorderRadius.circular(10)),
  child: Text(t, style: const TextStyle(color: Colors.grey)),
);

void main() {
  runApp(MaterialApp(
    theme: ThemeData(colorSchemeSeed: Colors.indigo, useMaterial3: true),
    home: Scaffold(
      body: Padding(
        padding: const EdgeInsets.all(28),
        child: Column(mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.stretch, children: [
          const Icon(Icons.school, size: 80, color: Colors.indigo),
          const Text('BrainBit Infotech Learner', textAlign: TextAlign.center, style: TextStyle(fontSize: 28, fontWeight: FontWeight.bold)),
          const Text('Sign in to continue', textAlign: TextAlign.center),
          const SizedBox(height: 28),
          field('Mobile number'),
          const SizedBox(height: 12),
          field('Password'),
          const SizedBox(height: 20),
          FilledButton(onPressed: () {}, child: const Text('LOGIN')),
          TextButton(onPressed: () {}, child: const Text('New student? Register')),
        ]),
      ),
    ),
  ));
}
Try it yourself: Change the app name, the icon and add a "Forgot password?" text below the button.
Add TextButton(onPressed: () {}, child: Text('Forgot password?')) in the list.

Quick quiz

3 questions. Click an answer.
Which method of a StatelessWidget returns the widgets to draw?
main()build()run()draw()
Which Container property puts space INSIDE the box?
marginpaddingalignmentwidth
Why do we write our own CourseTile widget?
To make the app slowerTo reuse one design many timesBecause Flutter forces itTo avoid Scaffold
Score: 0 / 3

Recap: what you learned in Module 5

StatelessWidget

A class with build() that draws fixed data.

Text + TextStyle

Size, weight, colour, spacing, decoration, overflow.

Container

margin, padding, decoration, size, child, alignment.

Scaffold

appBar, body, FAB, drawer: the frame of a screen.

Own widgets

Constructor data in, widgets out. Write once, reuse.

Theme

One seed colour styles the whole app; Theme.of(context) reads it.

Next: Layouts: Row, Column, Stack - Place widgets exactly where you want them
MODULE 6 · PART 2

Layouts: Row, Column, Stack

Place widgets exactly where you want them
You will learn
  • Row and Column: main axis and cross axis
  • Space things with Padding, SizedBox and Spacer
  • Share space with Expanded and Flexible
  • Layer widgets with Stack and Positioned
  • Wrap content and avoid overflow
You will build: a product card and a dashboard header
4 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
📐

Where is this used in real apps?

Design is mostly layout: where does the image go, how far is the price from the button, what happens on a small phone?

Row + Column

A WhatsApp chat row is a Row (photo, a Column with name and message, time).

Expanded

The search box takes all free space while the icons keep their size.

Stack

The red number badge on a cart icon, the "NEW" tag on a product photo.

Chats
👨
Rohit Singh
See you at 5 PM
10:42
👩
Asha Kumari
Notes sent
09:15
👪
Family group
Mummy: Dinner ready
Yesterday
🏫
Class 10 group
Test on Monday
Tue
+
💬
Chats
📞
Calls
⚙
Settings

The golden layout rule

Flutter layout has one rule: constraints go down, sizes go up, parent sets the position.

1. Parent gives limits

A parent tells its child: "you may be this wide and this tall at most".

2. Child picks a size

The child chooses its size inside those limits and reports it back up.

3. Parent places it

The parent decides where the child sits (centre, top-left, after the other child).

Why overflow happens: a child that wants more room than the parent gives. Example: a long Row of widgets wider than the phone. Fix it with Expanded, Wrap or scrolling.

Row and Column: two axes

Column goes top to bottom, Row goes left to right. Each has a main axis (its own direction) and a cross axis (the other direction).

mainAxisAlignment

start, center, end, spaceBetween, spaceAround, spaceEvenly: how children share the main axis.

crossAxisAlignment

start, center, end, stretch: where children sit on the cross axis.

mainAxisSize

min shrinks the Row/Column to its children; max (default) fills the space.

Memory trick: in a Column, main = vertical. In a Row, main = horizontal. The names always follow the widget.

Space: Padding, SizedBox, Spacer

Padding adds space around a child. SizedBox makes an empty gap (or fixes a size). Spacer takes all free room in a Row or Column.

EdgeInsets has many forms: all(16), symmetric(horizontal: 12), only(left: 8), fromLTRB(l,t,r,b).
Padding(
  padding: const EdgeInsets.all(16),   // space inside
  child: Column(children: const [
    Text('Title'),
    SizedBox(height: 12),               // gap between items
    Text('Subtitle'),
    SizedBox(height: 12),
    Row(children: [
      Text('Left'),
      Spacer(),                         // pushes next to right edge
      Text('Right'),
    ]),
  ]),
)

Center and Align

Center

Puts the child in the middle of the available space, both ways.

Align

Align(alignment: Alignment.bottomRight, child: ...) puts it at any of 9 spots.

Alignment values

topLeft, topCenter, topRight, centerLeft, center, centerRight, bottomLeft, bottomCenter, bottomRight.

Container alignment

Container(alignment: Alignment.center) does the same without a separate widget.

Real use: centre a loading spinner; put a "Skip" text at the top right of an onboarding page.

Expanded and Flexible

Expanded makes a child take the free space left in the Row or Column. flex shares that space in a ratio: flex 1 and flex 2 means 1/3 and 2/3.

Real use: a search box that takes all the width between a back icon and a mic icon.
Row(children: [
  Container(width: 60, height: 60, color: Colors.orange),   // fixed 60
  Expanded(
    flex: 1,                                                 // 1 share
    child: Container(height: 60, color: Colors.green),
  ),
  Expanded(
    flex: 2,                                                 // 2 shares
    child: Container(height: 60, color: Colors.blue),
  ),
])

Stack and Positioned: layers

Stack draws children on top of each other. Positioned places a child at exact distances from the edges. The last child is on top.

Real use: badge on a cart icon, text over an image, floating "play" button on a video thumbnail.
Stack(
  children: [
    Container(width: 200, height: 120, color: Colors.indigo.shade100),
    Positioned(
      top: 8, right: 8,
      child: Icon(Icons.favorite, color: Colors.red),
    ),
    Positioned(
      bottom: 8, left: 8,
      child: Text('Ranchi Falls', style: TextStyle(fontSize: 18)),
    ),
  ],
)

Wrap: automatic new lines

A Row that is too wide overflows. A Wrap starts a new line instead, like text in a paragraph.

spacing

Gap between items in one line.

runSpacing

Gap between lines.

Typical use

Tag chips, skills, size selectors (S M L XL), filter buttons.

Tip: Wrap is the quick fix when a Row of chips or buttons runs off the screen.

Debugging layout problems

Yellow-black stripes

On a real device this means overflow: a Row or Column is bigger than the space. Add Expanded, Wrap or a scroll view.

Nothing shows

Often a widget has size 0 or sits in a space with no height. Check Expanded/Container sizes.

Flutter DevTools

"Widget Inspector" shows each widget and its size. Switch on "Show guidelines".

Add colours

Temporarily give containers bright colours to see their real size.

Habit: build layouts from outside to inside: page, sections, rows, then small widgets.

Animated explainer: Main axis and cross axis

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

Animated explainer: Expanded shares the free space

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

Animated explainer: Stack layers

Press Next to walk through it step by step, or Auto play.
EASYReal project: stacking labels and fields on a formExample 1 of 10

Column alignment

mainAxisAlignment decides how a Column spreads its children vertically: start, center, or spaceBetween. The three boxes have the same children but different alignment.
Widget box(String t, MainAxisAlignment a) => Container(
  width: 100, height: 240, color: Colors.blue.shade50,
  child: Column(mainAxisAlignment: a, children: [
    Text(t, style: const TextStyle(fontWeight: FontWeight.bold)),
    const Icon(Icons.star), const Icon(Icons.star),
  ]),
);

void main() {
  runApp(MaterialApp(home: Scaffold(
    body: Padding(
      padding: const EdgeInsets.only(top: 60),
      child: Row(mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [
        box('start', MainAxisAlignment.start),
        box('center', MainAxisAlignment.center),
        box('between', MainAxisAlignment.spaceBetween),
      ]),
    ),
  )));
}
Try it yourself: Add a fourth box using MainAxisAlignment.end.
box('end', MainAxisAlignment.end) inside the Row. Make the boxes 80 wide to fit.
EASYReal project: icon bars, tab headers, price rowsExample 2 of 10

Row spacing options

A Row shares horizontal space in different ways. Compare spaceBetween, spaceAround and spaceEvenly with the same three squares.
Widget dot(Color c) => Container(width: 40, height: 40, color: c);

Widget rowDemo(String label, MainAxisAlignment a) => Column(children: [
  Text(label),
  Container(
    color: Colors.grey.shade200, margin: const EdgeInsets.all(8),
    child: Row(mainAxisAlignment: a, children: [
      dot(Colors.red), dot(Colors.green), dot(Colors.blue),
    ]),
  ),
]);

void main() {
  runApp(MaterialApp(home: Scaffold(
    body: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
      rowDemo('spaceBetween', MainAxisAlignment.spaceBetween),
      rowDemo('spaceAround', MainAxisAlignment.spaceAround),
      rowDemo('spaceEvenly', MainAxisAlignment.spaceEvenly),
    ]),
  )));
}
Try it yourself: Add a rowDemo for MainAxisAlignment.center.
rowDemo('center', MainAxisAlignment.center),
EASYReal project: spacing in forms and cardsExample 3 of 10

Padding and SizedBox

Padding keeps content away from the screen edge. SizedBox(height:) creates an even gap between lines, so you do not need empty Containers.
void main() {
  runApp(MaterialApp(home: Scaffold(
    body: Padding(
      padding: const EdgeInsets.all(24),
      child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        const SizedBox(height: 40),
        const Text('Admission Form', style: TextStyle(fontSize: 28, fontWeight: FontWeight.bold)),
        const SizedBox(height: 6),
        const Text('Fill all details carefully'),
        const SizedBox(height: 24),
        Container(height: 48, color: Colors.grey.shade300),
        const SizedBox(height: 12),
        Container(height: 48, color: Colors.grey.shade300),
        const SizedBox(height: 24),
        ElevatedButton(onPressed: () {}, child: const Text('Submit')),
      ]),
    ),
  )));
}
Try it yourself: Change the gap after the title from 24 to 50 and the padding from 24 to 12.
Edit the numbers in SizedBox(height: ...) and EdgeInsets.all(...).
EASYReal project: loader in the middle, "Skip" at a cornerExample 4 of 10

Center and Align

Align puts a child at one of nine positions inside its parent. Here the same Text is placed at three different spots inside three boxes.
Widget spot(String t, Alignment a) => Container(
  height: 120, margin: const EdgeInsets.fromLTRB(16, 12, 16, 0),
  color: Colors.teal.shade50,
  child: Align(alignment: a, child: Padding(
    padding: const EdgeInsets.all(8), child: Text(t))),
);

void main() {
  runApp(MaterialApp(home: Scaffold(
    body: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
      spot('topLeft', Alignment.topLeft),
      spot('center', Alignment.center),
      spot('bottomRight', Alignment.bottomRight),
    ]),
  )));
}
Try it yourself: Add a fourth box with Alignment.topRight.
spot('topRight', Alignment.topRight),
EASYReal project: header + body + footer of a pageExample 5 of 10

Expanded 1 : 2 and page layout

Expanded shares free space. First a Row with flex 1 and flex 2. Then the classic page: fixed header, Expanded body, fixed footer.
void main() {
  runApp(MaterialApp(home: Scaffold(
    body: Column(children: [
      Container(height: 70, color: Colors.indigo, alignment: Alignment.center,
          child: const Text('HEADER', style: TextStyle(color: Colors.white))),
      Row(children: [
        Expanded(flex: 1, child: Container(height: 60, color: Colors.orange, alignment: Alignment.center, child: const Text('1'))),
        Expanded(flex: 2, child: Container(height: 60, color: Colors.green, alignment: Alignment.center, child: const Text('2'))),
      ]),
      Expanded(child: Container(color: Colors.amber.shade100, alignment: Alignment.center,
          child: const Text('BODY takes all the rest'))),
      Container(height: 50, color: Colors.indigo, alignment: Alignment.center,
          child: const Text('FOOTER', style: TextStyle(color: Colors.white))),
    ]),
  )));
}
Try it yourself: Change the flex values to 3 and 1. Which colour is wider now?
Change flex: 1 to flex: 3 on the orange one.
MEDIUMReal project: cart / notification badgeExample 6 of 10

Stack badge on an icon

Stack layers widgets and Positioned pins the small red circle to the top-right corner of the icon. Every shopping app has this.
Widget badgeIcon(IconData icon, int count) => Stack(
  clipBehavior: Clip.none,
  children: [
    Icon(icon, size: 44, color: Colors.indigo),
    Positioned(
      right: -6, top: -4,
      child: Container(
        padding: const EdgeInsets.all(5),
        decoration: const BoxDecoration(color: Colors.red, shape: BoxShape.circle),
        child: Text('$count', style: const TextStyle(color: Colors.white, fontSize: 12)),
      ),
    ),
  ],
);

void main() {
  runApp(MaterialApp(home: Scaffold(
    appBar: AppBar(title: const Text('Ranchi Mart'), actions: [
      Padding(padding: const EdgeInsets.only(right: 20), child: badgeIcon(Icons.shopping_cart, 3)),
    ]),
    body: Center(child: badgeIcon(Icons.notifications, 12)),
  )));
}
Try it yourself: Make the badge blue and show the number 99.
color: Colors.blue in the BoxDecoration, and badgeIcon(Icons.mail, 99).
MEDIUMReal project: tags, skills, filtersExample 7 of 10

Wrap with skill chips

A Row of many chips runs off the screen. Wrap puts the extra chips on the next line. spacing is the gap on a line and runSpacing between lines.
void main() {
  const skills = ['Flutter', 'Dart', 'Firebase', 'REST API', 'Provider',
      'Git', 'SQLite', 'UI Design', 'Testing', 'Play Store'];
  runApp(MaterialApp(home: Scaffold(
    appBar: AppBar(title: const Text('My Skills')),
    body: Padding(
      padding: const EdgeInsets.all(16),
      child: Wrap(
        spacing: 8,
        runSpacing: 8,
        children: skills.map((s) => Chip(
          avatar: const Icon(Icons.check_circle, size: 18, color: Colors.green),
          label: Text(s),
        )).toList(),
      ),
    ),
  )));
}
Try it yourself: Add 3 more skills and try spacing: 20.
Add names to the skills list.
MEDIUMReal project: custom app header / bottom barExample 8 of 10

Spacer in a custom top bar

Spacer is an invisible Expanded. It pushes widgets apart so the menu sits left, the title in the middle and the search icon right.
Widget topBar() => Container(
  height: 60, padding: const EdgeInsets.symmetric(horizontal: 12),
  color: Colors.teal,
  child: const Row(children: [
    Icon(Icons.menu, color: Colors.white),
    Spacer(),
    Text('Ranchi Mart', style: TextStyle(color: Colors.white, fontSize: 20)),
    Spacer(),
    Icon(Icons.search, color: Colors.white),
    SizedBox(width: 12),
    Icon(Icons.shopping_cart, color: Colors.white),
  ]),
);

void main() {
  runApp(MaterialApp(home: Scaffold(
    body: Column(children: [
      topBar(),
      const Expanded(child: Center(child: Text('Page content'))),
      Padding(padding: const EdgeInsets.all(12), child: Row(children: [
        const Text('Total: Rs 855', style: TextStyle(fontSize: 18)),
        const Spacer(),
        ElevatedButton(onPressed: () {}, child: const Text('Pay now')),
      ])),
    ]),
  )));
}
Try it yourself: Remove the second Spacer. Where does the title go?
Without the second Spacer the title moves next to the search icons on the right.
HARDReal project: e-commerce product grid itemExample 9 of 10

Product card with a Stack

A real product card: a Stack for the photo with a discount tag and heart, then a Column for name, rating and price, and a Row with Spacer for the button. All layout tools together.
void main() {
  runApp(MaterialApp(home: Scaffold(
    backgroundColor: Colors.grey.shade200,
    body: Center(child: Container(
      width: 240,
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(16)),
      clipBehavior: Clip.antiAlias,
      child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [
        Stack(children: [
          Image.network('https://example.com/shoes.jpg', width: 240, height: 150, fit: BoxFit.cover),
          Positioned(top: 10, left: 10, child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
            color: Colors.red, child: const Text('30% OFF', style: TextStyle(color: Colors.white, fontSize: 12)))),
          const Positioned(top: 8, right: 8, child: Icon(Icons.favorite_border, color: Colors.white)),
        ]),
        Padding(padding: const EdgeInsets.all(12), child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          const Text('Running Shoes', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
          const Row(children: [Icon(Icons.star, size: 16, color: Colors.amber), Text(' 4.5 (212)')]),
          const SizedBox(height: 8),
          Row(children: [
            const Text('Rs 1,399', style: TextStyle(fontSize: 18, color: Colors.green)),
            const SizedBox(width: 6),
            const Text('Rs 1,999', style: TextStyle(decoration: TextDecoration.lineThrough, color: Colors.grey)),
            const Spacer(),
            Container(padding: const EdgeInsets.all(6), color: Colors.indigo, child: const Icon(Icons.add_shopping_cart, color: Colors.white, size: 20)),
          ]),
        ])),
      ]),
    )),
  )));
}
Try it yourself: Change the product to "School Bag", price Rs 649 and discount 20% OFF.
Edit the two prices and the Text in the red tag.
HARDReal project: home screen of a school / sales dashboardExample 10 of 10

Dashboard header

A gradient header with greeting row, then three equal stat cards using Expanded. Rows inside Columns inside Rows: normal for real dashboards.
Widget stat(String label, String value, Color c) => Expanded(child: Container(
  margin: const EdgeInsets.all(6), padding: const EdgeInsets.all(12),
  decoration: BoxDecoration(color: Colors.white24, borderRadius: BorderRadius.circular(14)),
  child: Column(children: [
    Text(value, style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: Colors.white)),
    Text(label, style: const TextStyle(color: Colors.white70, fontSize: 12)),
  ]),
));

void main() {
  runApp(MaterialApp(home: Scaffold(
    body: Column(children: [
      Container(
        padding: const EdgeInsets.fromLTRB(16, 44, 16, 16),
        decoration: const BoxDecoration(
          gradient: LinearGradient(colors: [Colors.indigo, Colors.blue]),
          borderRadius: BorderRadius.vertical(bottom: Radius.circular(24))),
        child: Column(children: [
          const Row(children: [
            CircleAvatar(radius: 24, backgroundColor: Colors.white, child: Text('NK')),
            SizedBox(width: 12),
            Expanded(child: Text('Hello, Nandan!', style: TextStyle(color: Colors.white, fontSize: 22))),
            Icon(Icons.notifications, color: Colors.white),
          ]),
          const SizedBox(height: 14),
          Row(children: [stat('Students', '128', Colors.white), stat('Batches', '6', Colors.white), stat('Fees due', '12', Colors.white)]),
        ]),
      ),
      const Expanded(child: Center(child: Text('Today\'s classes appear here'))),
    ]),
  )));
}
Try it yourself: Add a fourth stat card "Courses". What happens to the widths?
stat('Courses', '4', Colors.white), inside the Row. Expanded shares space equally.

Quick quiz

3 questions. Click an answer.
In a Row, the main axis is...
verticalhorizontaldiagonaldepth
Which widget takes all the free space left in a Row?
PaddingExpandedCenterIcon
Which widget layers children on top of each other?
ColumnRowStackWrap
Score: 0 / 3

Recap: what you learned in Module 6

Constraints

Parent gives limits, child picks size, parent places it.

Axes

Main axis follows the widget; cross axis is the other one.

Space

Padding, SizedBox and Spacer create room.

Expanded

flex shares free space in a ratio.

Stack

Layers with Positioned for badges and overlays.

Wrap

Starts a new line when the row is full.

Next: UI Components: Buttons, Cards, Chips - The ready-made parts every app is built from
MODULE 7 · PART 2

UI Components: Buttons, Cards, Chips

The ready-made parts every app is built from
You will learn
  • Pick the right button: Elevated, Outlined, Text, Icon
  • Show pictures with Image, ClipRRect and CircleAvatar
  • Build Card, ListTile and Divider rows
  • Use Chip, Badge-style tags and progress bars
  • Combine components into a real profile and menu
You will build: a contact card, a profile page and a menu card
4 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
🎨

Where is this used in real apps?

Open any app: buttons, cards, avatars and chips are on every screen. Learn these 10 parts and you can rebuild most screens.

Buttons

Pay now, Sign in, Add to cart: each is a button with a different style.

Card + ListTile

Contact lists, settings pages, order history rows.

Chip + Avatar

Filters like "Veg", profile pictures in a class group.

Ranchi Food
🍵
Litti Chokha
Rs 120
🍛
Dhuska
Rs 60
🍲
Veg Thali
Rs 150

Four kinds of buttons

Every button needs onPressed: the code that runs on tap. null makes the button grey and disabled.

Rule: one main (Elevated) button per screen; secondary actions use Outlined or Text buttons.
void main() {
  runApp(MaterialApp(home: Scaffold(body: Center(child: Column(children: [
  ElevatedButton(onPressed: () {}, child: const Text('Pay now')),
  OutlinedButton(onPressed: () {}, child: const Text('Cancel')),
  TextButton(onPressed: () {}, child: const Text('Forgot password?')),
  IconButton(onPressed: () {}, icon: const Icon(Icons.favorite)),
  ElevatedButton(onPressed: null, child: const Text('Disabled')),
])))));
}

Styling a button

styleFrom changes colour, size and shape of a button without writing a whole theme.

Tip: to style all buttons at once, use the app Theme (Module 12).
void main() {
  runApp(MaterialApp(home: Scaffold(body: Center(child: ElevatedButton(
  onPressed: () {},
  style: ElevatedButton.styleFrom(
    backgroundColor: Colors.green,
    foregroundColor: Colors.white,
    padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 14),
    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(30)),
  ),
  child: const Text('Order now'),
)))));
}

Image, ClipRRect, CircleAvatar

Image.network(url)

Loads a picture from the internet. Needs a width/height or a parent size.

Image.asset(path)

Loads a picture stored inside your app (declare it in pubspec.yaml).

ClipRRect

Cuts a child with rounded corners: ClipRRect(borderRadius: BorderRadius.circular(12), child: Image...).

CircleAvatar

A round picture or initials, used for profile photos.

fit: BoxFit.cover fills the box and crops extras. BoxFit.contain shows the whole picture.

Card and ListTile

Card is a rounded box with shadow. ListTile is a ready row: leading icon/photo, title, subtitle and trailing widget.

Real use: contact lists, settings rows, order history, notifications.
void main() {
  runApp(MaterialApp(home: Scaffold(body: Center(child: Card(
  elevation: 3,
  margin: const EdgeInsets.all(12),
  child: ListTile(
    leading: const CircleAvatar(child: Text('R')),
    title: const Text('Rohit Singh'),
    subtitle: const Text('Class 10 - Ranchi'),
    trailing: const Icon(Icons.call),
    onTap: () {},
  ),
)))));
}

Chip, Divider and Icon

Chip

A small label with optional icon: Chip(label: Text('Veg')).

Divider

A thin line between items: Divider() or Divider(thickness: 2).

Icon

Icon(Icons.home, size: 30, color: Colors.blue): over 2000 built-in icons.

LinearProgressIndicator

A bar showing progress from 0 to 1: value: 0.7 means 70%.

Real use: filter tags in a food app, fee-paid progress in a school app.

Text styling

TextStyle controls size, weight, colour and spacing. overflow: ellipsis shows "..." when text is too long.

Tip: long names in a list should always have maxLines and ellipsis.
void main() {
  runApp(MaterialApp(home: Scaffold(body: Center(child: const Text(
  'BrainBit Infotech',
  style: TextStyle(
    fontSize: 26,
    fontWeight: FontWeight.bold,
    color: Colors.indigo,
    letterSpacing: 1.5,
  ),
  textAlign: TextAlign.center,
  maxLines: 1,
  overflow: TextOverflow.ellipsis,
)))));
}

Animated explainer: Anatomy of a ListTile

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

Animated explainer: Which button to use?

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

Four button types

Flutter has several buttons. Elevated is the main one, Outlined and Text are quieter, IconButton is just an icon. onPressed: null disables a button.
void main() {
  runApp(MaterialApp(home: Scaffold(
    body: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
      ElevatedButton(onPressed: () {}, child: const Text('Pay now')),
      const SizedBox(height: 10),
      OutlinedButton(onPressed: () {}, child: const Text('Cancel')),
      const SizedBox(height: 10),
      TextButton(onPressed: () {}, child: const Text('Forgot password?')),
      IconButton(onPressed: () {}, icon: const Icon(Icons.favorite, color: Colors.red)),
      const ElevatedButton(onPressed: null, child: Text('Disabled')),
    ])),
  )));
}
Try it yourself: Add a TextButton that says "Skip".
TextButton(onPressed: () {}, child: const Text('Skip')),
EASYReal project: profile photo and product pictureExample 2 of 10

Rounded image and avatar

ClipRRect rounds the corners of an image. CircleAvatar makes a round photo. Here the pictures are placeholders because the browser has no internet.
void main() {
  runApp(MaterialApp(home: Scaffold(
    body: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
      const CircleAvatar(radius: 44, backgroundColor: Colors.teal,
          child: Text('AK', style: TextStyle(fontSize: 28, color: Colors.white))),
      const SizedBox(height: 20),
      ClipRRect(
        borderRadius: BorderRadius.circular(20),
        child: Image.network('https://example.com/ranchi.jpg',
            width: 220, height: 140, fit: BoxFit.cover),
      ),
    ])),
  )));
}
Try it yourself: Change the avatar to radius 60 and colour orange.
radius: 60, backgroundColor: Colors.orange
EASYReal project: contact or student listExample 3 of 10

Card with ListTile

Card + ListTile is the fastest way to build a good-looking row. leading, title, subtitle and trailing are ready slots.
void main() {
  runApp(MaterialApp(home: Scaffold(
    appBar: AppBar(title: const Text('My Contacts')),
    body: Column(children: [
      Card(margin: const EdgeInsets.fromLTRB(12, 12, 12, 0), child: ListTile(
        leading: const CircleAvatar(child: Text('R')),
        title: const Text('Rohit Singh'), subtitle: const Text('Doranda, Ranchi'),
        trailing: const Icon(Icons.call, color: Colors.green))),
      Card(margin: const EdgeInsets.fromLTRB(12, 8, 12, 0), child: ListTile(
        leading: const CircleAvatar(child: Text('A')),
        title: const Text('Asha Kumari'), subtitle: const Text('Kankarbagh, Patna'),
        trailing: const Icon(Icons.call, color: Colors.green))),
    ]),
  )));
}
Try it yourself: Add a third contact "Imran Ansari, Hatia".
Copy one Card and change the names.
EASYReal project: filters in a food or course appExample 4 of 10

Chips and Divider

Chip shows a small tag. Divider draws a thin separator. Together they group information neatly.
void main() {
  runApp(MaterialApp(home: Scaffold(
    body: Padding(padding: const EdgeInsets.all(20), child: Column(
      crossAxisAlignment: CrossAxisAlignment.start, children: [
        const SizedBox(height: 40),
        const Text('Filter by diet', style: TextStyle(fontSize: 22)),
        const SizedBox(height: 10),
        const Wrap(spacing: 8, children: [
          Chip(label: Text('Veg')), Chip(label: Text('Jain')), Chip(label: Text('Spicy')),
        ]),
        const Divider(height: 32, thickness: 1.5),
        const Text('Sort by', style: TextStyle(fontSize: 22)),
        const SizedBox(height: 10),
        const Wrap(spacing: 8, children: [
          Chip(avatar: Icon(Icons.star, size: 16), label: Text('Rating')),
          Chip(avatar: Icon(Icons.currency_rupee, size: 16), label: Text('Price')),
        ]),
      ])),
  )));
}
Try it yourself: Add a Chip "Sweet" to the diet list.
Chip(label: Text('Sweet')) inside the first Wrap.
EASYReal project: fee paid, upload and loading screensExample 5 of 10

Progress indicators

LinearProgressIndicator(value: 0.7) shows 70%. Without value it spins forever (loading). Percentages are shown with a Text beside it.
void main() {
  const paid = 18000;
  const total = 24000;
  final percent = paid / total;
  runApp(MaterialApp(home: Scaffold(
    body: Padding(padding: const EdgeInsets.all(24), child: Column(
      mainAxisAlignment: MainAxisAlignment.center, children: [
        Text('Fees paid: Rs $paid of Rs $total'),
        const SizedBox(height: 12),
        LinearProgressIndicator(value: percent, minHeight: 12, color: Colors.green),
        const SizedBox(height: 8),
        Text('${(percent * 100).toStringAsFixed(0)}% complete'),
        const SizedBox(height: 40),
        const CircularProgressIndicator(),
        const Text('Loading...'),
      ])),
  )));
}
Try it yourself: Change paid to 12000. What percent do you see?
const paid = 12000; It shows 50%.
MEDIUMReal project: contact or business card screenExample 6 of 10

Contact card

A full contact card built from Card, CircleAvatar, Text and three Icon buttons, all laid out with Column and Row.
Widget action(IconData i, String t, Color c) => Column(children: [
  CircleAvatar(backgroundColor: c.withOpacity(0.15), child: Icon(i, color: c)),
  const SizedBox(height: 4), Text(t, style: const TextStyle(fontSize: 12)),
]);

void main() {
  runApp(MaterialApp(home: Scaffold(body: Center(child: Card(
    margin: const EdgeInsets.all(20), elevation: 4,
    child: Padding(padding: const EdgeInsets.all(20), child: Column(mainAxisSize: MainAxisSize.min, children: [
      const CircleAvatar(radius: 40, child: Text('SK', style: TextStyle(fontSize: 26))),
      const SizedBox(height: 12),
      const Text('Sunita Kumari', style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold)),
      const Text('Teacher, DAV School Ranchi'),
      const Divider(height: 28),
      Row(mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [
        action(Icons.call, 'Call', Colors.green), action(Icons.message, 'SMS', Colors.blue), action(Icons.mail, 'Email', Colors.red),
      ]),
    ])),
  )))));
}
Try it yourself: Add a fourth action: Icons.share, "Share".
action(Icons.share, 'Share', Colors.orange),
MEDIUMReal project: bill / order summary screenExample 7 of 10

Receipt with dividers

A receipt shows rows of name and price. A Row with Spacer puts the price at the right. The total is calculated in code from a list.
Widget line(String n, int p) => Padding(
  padding: const EdgeInsets.symmetric(vertical: 6),
  child: Row(children: [Text(n), const Spacer(), Text('Rs $p')]),
);

void main() {
  final items = {'Litti Chokha': 120, 'Dhuska': 60, 'Lassi': 40};
  int total = 0;
  items.forEach((k, v) => total += v);
  runApp(MaterialApp(home: Scaffold(
    appBar: AppBar(title: const Text('Order Bill')),
    body: Padding(padding: const EdgeInsets.all(20), child: Column(children: [
      ...items.entries.map((e) => line(e.key, e.value)),
      const Divider(thickness: 2),
      Row(children: [
        const Text('Total', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
        const Spacer(),
        Text('Rs $total', style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Colors.green)),
      ]),
    ])),
  )));
}
Try it yourself: Add "Jalebi": 30 to the map. Does the total change?
Add to the items map: 'Jalebi': 30. The total becomes 250.
MEDIUMReal project: course or skill progress pageExample 8 of 10

Progress with percent labels

A list of subjects, each with a progress bar. Data lives in a list of maps and the UI is created with map(), so adding a subject needs one line only.
void main() {
  final subjects = [
    {'name': 'Flutter', 'done': 0.8},
    {'name': 'Dart', 'done': 0.95},
    {'name': 'Firebase', 'done': 0.35},
  ];
  runApp(MaterialApp(home: Scaffold(
    appBar: AppBar(title: const Text('My Progress')),
    body: Padding(padding: const EdgeInsets.all(20), child: Column(
      children: subjects.map((s) {
        final d = s['done'] as double;
        return Padding(padding: const EdgeInsets.only(bottom: 18), child: Column(
          crossAxisAlignment: CrossAxisAlignment.start, children: [
            Row(children: [Text(s['name'] as String), const Spacer(), Text('${(d * 100).toStringAsFixed(0)}%')]),
            const SizedBox(height: 6),
            LinearProgressIndicator(value: d, minHeight: 10),
          ]));
      }).toList(),
    )),
  )));
}
Try it yourself: Add {'name': 'Git', 'done': 0.5}.
Add the map to the subjects list.
HARDReal project: "My account" screen of any appExample 9 of 10

Profile page

A real profile: gradient header with avatar, three stats, then Card rows with ListTile for settings. Every part is a component from this module.
Widget stat(String v, String l) => Column(children: [
  Text(v, style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Colors.white)),
  Text(l, style: const TextStyle(color: Colors.white70, fontSize: 12)),
]);
Widget row(IconData i, String t) => Card(margin: const EdgeInsets.fromLTRB(16, 8, 16, 0),
  child: ListTile(leading: Icon(i, color: Colors.indigo), title: Text(t), trailing: const Icon(Icons.chevron_right)));

void main() {
  runApp(MaterialApp(home: Scaffold(body: Column(children: [
    Container(width: double.infinity, padding: const EdgeInsets.fromLTRB(16, 48, 16, 20),
      color: Colors.indigo, child: Column(children: [
        const CircleAvatar(radius: 38, backgroundColor: Colors.white, child: Text('NK', style: TextStyle(fontSize: 24))),
        const SizedBox(height: 10),
        const Text('Nandan Kumar', style: TextStyle(color: Colors.white, fontSize: 22)),
        const SizedBox(height: 14),
        Row(mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [stat('128', 'Students'), stat('6', 'Batches'), stat('4.9', 'Rating')]),
    ])),
    const SizedBox(height: 8),
    row(Icons.person, 'Edit profile'), row(Icons.notifications, 'Notifications'),
    row(Icons.lock, 'Privacy'), row(Icons.help, 'Help and support'),
  ]))));
}
Try it yourself: Add a "Log out" row with Icons.logout.
row(Icons.logout, 'Log out'),
HARDReal project: food delivery / canteen appExample 10 of 10

Menu card for a restaurant

A menu from a data list: each dish is a Card with an emoji, name, price and a veg/non-veg chip. One function builds every card, so 100 dishes cost no extra code.
Widget dish(String e, String n, int p, bool veg) => Card(
  margin: const EdgeInsets.fromLTRB(14, 8, 14, 0),
  child: Padding(padding: const EdgeInsets.all(12), child: Row(children: [
    Text(e, style: const TextStyle(fontSize: 36)),
    const SizedBox(width: 12),
    Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      Text(n, style: const TextStyle(fontSize: 17, fontWeight: FontWeight.bold)),
      Chip(label: Text(veg ? 'Veg' : 'Non-veg'),
          backgroundColor: veg ? Colors.green.shade100 : Colors.red.shade100),
    ])),
    Column(children: [
      Text('Rs $p', style: const TextStyle(fontSize: 16, color: Colors.green)),
      ElevatedButton(onPressed: () {}, child: const Text('Add')),
    ]),
  ])),
);

void main() {
  runApp(MaterialApp(home: Scaffold(
    appBar: AppBar(title: const Text('Ranchi Rasoi')),
    body: Column(children: [
      dish('\u{1F35B}', 'Litti Chokha', 120, true),
      dish('\u{1F357}', 'Chicken Curry', 220, false),
      dish('\u{1F35A}', 'Dal Bhat', 90, true),
    ]),
  )));
}
Try it yourself: Add a fourth dish: Dhuska, Rs 60, veg.
dish('\u{1F35E}', 'Dhuska', 60, true),

Quick quiz

3 questions. Click an answer.
Which button should be the main action on a screen?
TextButtonElevatedButtonIconButtonChip
Which widget gives leading, title, subtitle and trailing slots?
ContainerListTileWrapStack
What does onPressed: null do?
Crashes the appDisables the buttonHides itMakes it bigger
Score: 0 / 3

Recap: what you learned in Module 7

Buttons

Elevated for main, Outlined/Text for others, IconButton for icons.

Images

Image.network/asset, ClipRRect for corners, CircleAvatar for photos.

Card + ListTile

Ready rows with four slots.

Chip

Small tags and filters.

Progress

LinearProgressIndicator(value) for percentages.

Compose

Big screens are small components combined.

Next: Lists, Grids and Scrolling - Show 10 or 10,000 items with the same code
MODULE 8 · PART 2

Lists, Grids and Scrolling

Show 10 or 10,000 items with the same code
You will learn
  • Show a scrolling list with ListView
  • Build items from data with ListView.builder
  • Make grids with GridView
  • Separate rows and scroll sideways
  • Combine lists and grids into a real feed
You will build: a chat screen and a news feed
4 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
📜

Where is this used in real apps?

Almost every screen is a list: contacts, chats, products, orders, news. Flutter builds only what is visible, so even a huge list stays fast.

ListView

WhatsApp chats, contact list, notification page.

GridView

Product grid in Amazon, photo gallery.

Horizontal list

Story circles, category chips at the top of a shop.

News
📰
Ranchi gets new flyover
Traffic to ease near Kutchery
1h
🏏
JSCA stadium match
Tickets from Rs 200
3h
🌧
Monsoon update
Heavy rain in Jharkhand
5h
🏫
Board results out
Check scores online
1d
+
🏠
Home
🔍
Search
🔖
Saved

ListView: a scrolling column

A Column does not scroll and overflows. A ListView scrolls when it has more children than fit.

Rule: if the number of items can be large or unknown, use a ListView, never a Column.
void main() {
  runApp(MaterialApp(home: Scaffold(body: ListView(
  children: const [
    ListTile(leading: Icon(Icons.home), title: Text('Home')),
    ListTile(leading: Icon(Icons.school), title: Text('Courses')),
    ListTile(leading: Icon(Icons.person), title: Text('Profile')),
    ListTile(leading: Icon(Icons.settings), title: Text('Settings')),
  ],
))));
}

ListView.builder: from data

builder creates each row only when it scrolls into view. itemCount says how many, itemBuilder builds row number index.

Real use: 5000 products from a server show up instantly, because only about 10 rows exist at a time.
final names = ['Rohit', 'Asha', 'Imran', 'Pooja'];

void main() {
  runApp(MaterialApp(home: Scaffold(body: ListView.builder(
  itemCount: names.length,
  itemBuilder: (context, index) {
    return ListTile(
      leading: CircleAvatar(child: Text(names[index][0])),
      title: Text(names[index]),
    );
  },
))));
}

GridView: rows and columns

GridView.count makes a grid with a fixed number of columns. Change crossAxisCount to 3 and the grid re-flows.

Real use: product grid, photo gallery, app icons, dashboard tiles.
void main() {
  runApp(MaterialApp(home: Scaffold(body: GridView.count(
  crossAxisCount: 2,
  crossAxisSpacing: 10,
  mainAxisSpacing: 10,
  padding: const EdgeInsets.all(12),
  children: List.generate(6, (i) => Container(
    color: Colors.indigo.shade100,
    alignment: Alignment.center,
    child: Text('Item ${i + 1}'),
  )),
))));
}

Horizontal, separated and scroll rules

Horizontal list

ListView(scrollDirection: Axis.horizontal) scrolls sideways. Give it a fixed height.

ListView.separated

Like builder, plus separatorBuilder to draw a Divider between rows.

shrinkWrap

Makes a ListView only as tall as its children. Needed inside a Column, but use it only for short lists.

SingleChildScrollView

Makes any Column scroll. Good for forms; not for long data lists.

Error to remember: "Vertical viewport was given unbounded height" means a ListView sits inside a Column. Wrap the ListView in Expanded.

Which scroll widget?

Few fixed items

ListView with children.

Many or server data

ListView.builder.

Tiles in columns

GridView.count or GridView.builder.

A form or a mixed page

SingleChildScrollView + Column.

Pull to refresh

Wrap a list with RefreshIndicator (more in Module 14).

Memory trick: data = builder, page = SingleChildScrollView.

Animated explainer: Why builder is fast

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

Animated explainer: Grid columns

Press Next to walk through it step by step, or Auto play.
EASYReal project: settings or menu pageExample 1 of 10

Simple ListView

A ListView with fixed children is a scrolling menu. Add more tiles than fit and it scrolls on its own.
void main() {
  runApp(MaterialApp(home: Scaffold(
    appBar: AppBar(title: const Text('Menu')),
    body: ListView(children: const [
      ListTile(leading: Icon(Icons.home), title: Text('Home')),
      ListTile(leading: Icon(Icons.school), title: Text('My Courses')),
      ListTile(leading: Icon(Icons.assignment), title: Text('Assignments')),
      ListTile(leading: Icon(Icons.payment), title: Text('Fees')),
      ListTile(leading: Icon(Icons.event), title: Text('Attendance')),
      ListTile(leading: Icon(Icons.notifications), title: Text('Notices')),
      ListTile(leading: Icon(Icons.person), title: Text('Profile')),
      ListTile(leading: Icon(Icons.settings), title: Text('Settings')),
      ListTile(leading: Icon(Icons.logout), title: Text('Log out')),
    ]),
  )));
}
Try it yourself: Add a "Help" tile with Icons.help.
ListTile(leading: Icon(Icons.help), title: Text('Help')),
EASYReal project: any list from dataExample 2 of 10

ListView.builder

builder makes rows from a list. Here 50 roll numbers are generated; only the visible ones are built.
void main() {
  runApp(MaterialApp(home: Scaffold(
    appBar: AppBar(title: const Text('Class 10-A')),
    body: ListView.builder(
      itemCount: 50,
      itemBuilder: (context, i) => ListTile(
        leading: CircleAvatar(child: Text('${i + 1}')),
        title: Text('Student roll no ${i + 1}'),
      ),
    ),
  )));
}
Try it yourself: Change itemCount to 5.
itemCount: 5
EASYReal project: contact app, student listExample 3 of 10

Contacts from a list

Real apps keep data in a List and the builder turns every entry into a row. To add a person, add one string to the list.
void main() {
  final people = ['Rohit Singh', 'Asha Kumari', 'Imran Ansari', 'Pooja Oraon', 'Suresh Mahto', 'Anita Devi'];
  runApp(MaterialApp(home: Scaffold(
    appBar: AppBar(title: const Text('Contacts')),
    body: ListView.builder(
      itemCount: people.length,
      itemBuilder: (context, i) => ListTile(
        leading: CircleAvatar(child: Text(people[i][0])),
        title: Text(people[i]),
        subtitle: Text('98765${10000 + i * 111}'),
        trailing: const Icon(Icons.call, color: Colors.green),
      ),
    ),
  )));
}
Try it yourself: Add "Deepak Prasad" to the list.
Add the name to people.
EASYReal project: product or photo galleryExample 4 of 10

GridView.count

GridView.count arranges tiles in columns. Change crossAxisCount to see 2, 3 or 4 columns.
void main() {
  final colors = [Colors.red, Colors.orange, Colors.green, Colors.blue, Colors.purple, Colors.teal, Colors.pink, Colors.indigo];
  runApp(MaterialApp(home: Scaffold(
    appBar: AppBar(title: const Text('Gallery')),
    body: GridView.count(
      crossAxisCount: 2,
      crossAxisSpacing: 10, mainAxisSpacing: 10,
      padding: const EdgeInsets.all(12),
      children: List.generate(8, (i) => Container(
        decoration: BoxDecoration(color: colors[i], borderRadius: BorderRadius.circular(12)),
        alignment: Alignment.center,
        child: Text('Photo ${i + 1}', style: const TextStyle(color: Colors.white, fontSize: 18)),
      )),
    ),
  )));
}
Try it yourself: Change crossAxisCount to 3.
crossAxisCount: 3
EASYReal project: categories and stories at top of a shopExample 5 of 10

Horizontal list

Set scrollDirection: Axis.horizontal and give the list a fixed height. Swipe sideways to see more.
void main() {
  const cats = ['Mobiles', 'Fashion', 'Grocery', 'Books', 'Toys', 'Sports', 'Home'];
  runApp(MaterialApp(home: Scaffold(
    appBar: AppBar(title: const Text('Ranchi Mart')),
    body: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      const Padding(padding: EdgeInsets.all(14), child: Text('Shop by category', style: TextStyle(fontSize: 20))),
      SizedBox(height: 56, child: ListView.builder(
        scrollDirection: Axis.horizontal,
        padding: const EdgeInsets.symmetric(horizontal: 10),
        itemCount: cats.length,
        itemBuilder: (c, i) => Padding(padding: const EdgeInsets.only(right: 8), child: Chip(label: Text(cats[i]))),
      )),
    ]),
  )));
}
Try it yourself: Add "Medicine" to cats.
Add the word to the cats list.
MEDIUMReal project: order history, notification listExample 6 of 10

ListView.separated

separated draws a divider between rows without extra code. The item number is shown with the amount.
void main() {
  final orders = {'Order #1021': 450, 'Order #1020': 1299, 'Order #1019': 220, 'Order #1018': 89, 'Order #1017': 640};
  final keys = orders.keys.toList();
  runApp(MaterialApp(home: Scaffold(
    appBar: AppBar(title: const Text('My Orders')),
    body: ListView.separated(
      itemCount: keys.length,
      separatorBuilder: (c, i) => const Divider(height: 1),
      itemBuilder: (c, i) => ListTile(
        leading: const Icon(Icons.shopping_bag, color: Colors.indigo),
        title: Text(keys[i]),
        subtitle: const Text('Delivered'),
        trailing: Text('Rs ${orders[keys[i]]}'),
      ),
    ),
  )));
}
Try it yourself: Add 'Order #1016': 150.
Add the pair to the orders map.
MEDIUMReal project: e-commerce home pageExample 7 of 10

Product grid with builder

GridView.builder with childAspectRatio makes tall cards. A product map becomes a card with name and price: the same pattern every shop app uses.
void main() {
  final products = [['School Bag', 649], ['Water Bottle', 199], ['Notebook Set', 120], ['Geometry Box', 85], ['Lunch Box', 249], ['Pen Pack', 60]];
  runApp(MaterialApp(home: Scaffold(
    appBar: AppBar(title: const Text('Stationery Shop')),
    body: GridView.builder(
      padding: const EdgeInsets.all(12),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2, crossAxisSpacing: 10, mainAxisSpacing: 10, childAspectRatio: 0.85),
      itemCount: products.length,
      itemBuilder: (c, i) => Card(child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
        const Icon(Icons.inventory_2, size: 42, color: Colors.indigo),
        const SizedBox(height: 8),
        Text(products[i][0] as String, style: const TextStyle(fontWeight: FontWeight.bold)),
        Text('Rs ${products[i][1]}', style: const TextStyle(color: Colors.green)),
      ])),
    ),
  )));
}
Try it yourself: Change childAspectRatio to 1.2. What happens to the cards?
They become wider and shorter.
MEDIUMReal project: news or blog article screenExample 8 of 10

Scrollable article page

A page mixing a heading, text and a button needs SingleChildScrollView. Long text then scrolls instead of overflowing.
void main() {
  final paragraph = 'Ranchi is the capital of Jharkhand. It is known as the City of Waterfalls because of Hundru, Dassam and Jonha falls nearby. ';
  runApp(MaterialApp(home: Scaffold(
    appBar: AppBar(title: const Text('Know Ranchi')),
    body: SingleChildScrollView(padding: const EdgeInsets.all(16), child: Column(
      crossAxisAlignment: CrossAxisAlignment.start, children: [
        Container(height: 140, color: Colors.teal.shade100, alignment: Alignment.center, child: const Icon(Icons.landscape, size: 60)),
        const SizedBox(height: 12),
        const Text('City of Waterfalls', style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold)),
        const SizedBox(height: 8),
        Text(paragraph * 6),
        const SizedBox(height: 12),
        Center(child: ElevatedButton(onPressed: () {}, child: const Text('Share article'))),
      ])),
  )));
}
Try it yourself: Change the paragraph multiplier from 6 to 2.
paragraph * 2
HARDReal project: WhatsApp-style messagingExample 9 of 10

Chat screen

A chat is a ListView of message bubbles. Mine and theirs are aligned left or right with Align, and a bottom bar holds the input and send icon.
Widget bubble(String t, bool me) => Align(
  alignment: me ? Alignment.centerRight : Alignment.centerLeft,
  child: Container(
    margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
    padding: const EdgeInsets.all(10),
    constraints: const BoxConstraints(maxWidth: 220),
    decoration: BoxDecoration(
      color: me ? Colors.green.shade200 : Colors.grey.shade300,
      borderRadius: BorderRadius.circular(14)),
    child: Text(t),
  ),
);

void main() {
  final msgs = [['Hi Rohit, class at 5?', true], ['Yes sir, I will come', false], ['Bring your laptop', true], ['Ok sir', false]];
  runApp(MaterialApp(home: Scaffold(
    appBar: AppBar(title: const Text('Rohit Singh')),
    body: Column(children: [
      Expanded(child: ListView.builder(
        padding: const EdgeInsets.only(top: 10),
        itemCount: msgs.length,
        itemBuilder: (c, i) => bubble(msgs[i][0] as String, msgs[i][1] as bool),
      )),
      Padding(padding: const EdgeInsets.all(8), child: Row(children: [
        Expanded(child: Container(padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(color: Colors.grey.shade200, borderRadius: BorderRadius.circular(24)),
            child: const Text('Type a message'))),
        const SizedBox(width: 8),
        const CircleAvatar(child: Icon(Icons.send)),
      ])),
    ]),
  )));
}
Try it yourself: Add one more message from me: "See you".
Add ['See you', true] to msgs.
HARDReal project: news / social feedExample 10 of 10

News feed with categories

A full home screen: category chips scroll sideways on top, a vertical list of article cards below. Two lists inside one Column, the lower one wrapped in Expanded.
void main() {
  const cats = ['All', 'Sports', 'Weather', 'Education', 'Jobs', 'Business'];
  final news = [['Ranchi gets a new flyover', 'City'], ['JSCA match tickets open', 'Sports'], ['Heavy rain alert for Jharkhand', 'Weather'], ['Board results announced', 'Education'], ['Walk-in drive at Namkum', 'Jobs']];
  runApp(MaterialApp(home: Scaffold(
    appBar: AppBar(title: const Text('Ranchi Samachar')),
    body: Column(children: [
      SizedBox(height: 52, child: ListView.builder(
        scrollDirection: Axis.horizontal, padding: const EdgeInsets.all(8), itemCount: cats.length,
        itemBuilder: (c, i) => Padding(padding: const EdgeInsets.only(right: 8),
            child: Chip(label: Text(cats[i]), backgroundColor: i == 0 ? Colors.indigo.shade100 : null)),
      )),
      Expanded(child: ListView.builder(
        itemCount: news.length,
        itemBuilder: (c, i) => Card(margin: const EdgeInsets.fromLTRB(12, 4, 12, 4), child: ListTile(
          leading: Container(width: 56, height: 56, color: Colors.indigo.shade50, child: const Icon(Icons.article)),
          title: Text(news[i][0]), subtitle: Text(news[i][1]),
          trailing: const Icon(Icons.bookmark_border),
        )),
      )),
    ]),
  )));
}
Try it yourself: Add a news item for category "Business".
Add ['Gold price rises', 'Business'] to news.

Quick quiz

3 questions. Click an answer.
Which widget builds rows only when they scroll into view?
ColumnListView.builderRowStack
A ListView inside a Column gives an unbounded height error. Fix?
Wrap it in ExpandedDelete the ColumnUse StackUse Padding
How do you make a list scroll sideways?
scrollDirection: Axis.horizontalUse Row onlyflex: 2shrinkWrap: true
Score: 0 / 3

Recap: what you learned in Module 8

ListView

Scrolls when content is too long.

builder

Builds rows on demand from data: fast for large lists.

GridView

count / builder for tiles in columns.

Horizontal

scrollDirection + fixed height.

Expanded

Fixes lists inside a Column.

SingleChildScrollView

For pages and forms.

Next: the next part of the course.

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