FLUTTER WIDGETS & DESIGN COURSE · BRAINBIT INFOTECH

Part 1

4 modules · 18 class hours · 40 practical examples

Module 21: Widget Tree, Constraints and Keys

How Flutter really draws your screen · 4 h

Module 22: Text and Typography

Make every word look right · 4 h

Module 23: Containers and Decoration

Cards, gradients, shadows and shapes · 5 h

Module 24: Layout Widgets: Row, Column, Stack and more

Place everything exactly where you want · 5 h

MODULE 21 · PART 1

Widget Tree, Constraints and Keys

How Flutter really draws your screen
You will learn
  • See every screen as a tree of widgets
  • Build your own reusable StatelessWidget
  • Understand "constraints go down, sizes go up"
  • Use BuildContext, Theme.of and MediaQuery.of
  • Use keys so state stays with the right widget
You will build: reusable widgets and a small school dashboard
4 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
🌳

Where is this used in real apps?

Every Flutter screen, from a tea-shop menu to a bank app, is one big tree of small widgets. If you can read the tree, you can fix any layout bug.

Widget

A small description of a piece of screen: Text, Padding, Row, your own ProfileCard.

Constraints

The parent tells the child how big it may be. The child picks a size inside that.

Key

A name tag that helps Flutter match old widgets with new ones when a list changes.

Ranchi Bazaar
🍲
Dhuska corner
Rs 20
🥚
Sattu drink
Rs 15
🍵
Chai
Rs 10
🍚
Litti
Rs 25

Everything is a widget

In Flutter a screen is built by putting small widgets inside bigger widgets. The result is a tree: one root at the top and branches below it. A Text inside a Padding inside a Center inside a Scaffold is a four-level tree.

Read the tree from the outside in. Each widget has one parent. Widgets like Column and Row have many children.
void main() {
  runApp(const MaterialApp(
    home: Scaffold(                      // level 1
      body: Center(                      // level 2
        child: Padding(                  // level 3
          padding: EdgeInsets.all(24),
          child: Text('Namaste Ranchi',  // level 4
              style: TextStyle(fontSize: 32)),
        ),
      ),
    ),
  ));
}

Your own widget = a class

When a piece of screen repeats, put it in its own class. A StatelessWidget receives values through its constructor and returns a widget tree from build().

Naming rule: class names start with a capital letter (ShopCard). The file name uses small letters (shop_card.dart).
class ShopCard extends StatelessWidget {
  final String name;
  final int price;
  const ShopCard(this.name, this.price, {super.key});

  @override
  Widget build(BuildContext context) {
    return Card(
      child: ListTile(
        leading: const Icon(Icons.store),
        title: Text(name),
        trailing: Text('Rs $price'),
      ),
    );
  }
}

void main() {
  runApp(const MaterialApp(home: Scaffold(
    body: Column(children: [
      ShopCard('Dhuska plate', 40),
      ShopCard('Litti chokha', 60),
    ]),
  )));
}

Constraints go down, sizes go up

This one rule explains almost every layout surprise.

Why width: 100 sometimes does nothing: a parent with tight constraints ignores the size you asked for.
void main() {
  runApp(MaterialApp(home: Scaffold(
    body: Column(children: [
      // no Center: Scaffold body is tight, Container fills it
      Container(color: Colors.red, height: 60),
      // inside Center the constraints become loose
      Center(child: Container(color: Colors.green, width: 120, height: 60)),
      // ConstrainedBox limits the maximum width
      ConstrainedBox(
        constraints: const BoxConstraints(maxWidth: 200),
        child: Container(color: Colors.blue, height: 60),
      ),
    ]),
  )));
}

BuildContext: where am I in the tree?

context is the address of your widget inside the tree. Flutter uses it to look upwards: the nearest Theme, the screen size, the nearest Navigator.

Common error: using a context that sits ABOVE the Scaffold. Wrap the part in a Builder or move it into its own widget class.
class Info extends StatelessWidget {
  const Info({super.key});
  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    final color = Theme.of(context).colorScheme.primary;
    return Center(
      child: Text('Screen ${size.width.toInt()} x ${size.height.toInt()}',
          style: TextStyle(fontSize: 24, color: color)),
    );
  }
}

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

Keys: name tags for widgets

When a list is reordered, Flutter compares old and new widgets by type and position. Stateful widgets can then keep the wrong state. A ValueKey tells Flutter which widget is which.

ValueKey(x)

Use a unique value such as an id or name.

UniqueKey()

A new key every build. Forces a fresh widget.

GlobalKey

Reach a widget from far away (Forms use it).

No key needed

For a static list that never reorders.

Rule of thumb: if your list can be sorted, filtered or reordered and the items hold state, give each item a ValueKey.

Animated explainer: Three trees working together

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

Animated explainer: Constraints go down, sizes go up

Press Next to walk through it step by step, or Auto play.
EASYReal project: any screen you buildExample 1 of 10

Reading a widget tree

A tiny screen with five widgets. Count them: Scaffold, AppBar, Center, Column, Text. Every Flutter screen is made the same way.
void main() {
  runApp(const MaterialApp(
    home: Scaffold(
      appBar: AppBar(title: Text('Ranchi Weather')),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(Icons.wb_sunny, size: 64, color: Colors.orange),
            Text('28 C, sunny', style: TextStyle(fontSize: 28)),
          ],
        ),
      ),
    ),
  ));
}
Try it yourself: Add a third child: Text("Humidity 60%").
Add it to the children list under the Text.
EASYReal project: profile card, product tileExample 2 of 10

Your first custom widget

ShopCard is a StatelessWidget that takes a name and a price. You write it once and use it anywhere.
class ShopCard extends StatelessWidget {
  final String name;
  final int price;
  const ShopCard(this.name, this.price, {super.key});
  @override
  Widget build(BuildContext context) => Card(
    margin: const EdgeInsets.all(12),
    child: ListTile(
      leading: const Icon(Icons.store, color: Colors.teal),
      title: Text(name),
      subtitle: const Text('Main Road, Ranchi'),
      trailing: Text('Rs $price', style: const TextStyle(fontWeight: FontWeight.bold)),
    ),
  );
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Center(child: ShopCard('Dhuska plate', 40)))));
Try it yourself: Add an address parameter instead of the fixed "Main Road".
Add final String address; and use Text(address).
EASYReal project: product list, contact listExample 3 of 10

Reuse one widget three times

The same ShopCard class draws three different shops. If you change the card design, all three change together.
class ShopCard extends StatelessWidget {
  final String name, item;
  final int price;
  const ShopCard(this.name, this.item, this.price, {super.key});
  @override
  Widget build(BuildContext context) => Card(
    margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
    child: ListTile(
      title: Text(name),
      subtitle: Text(item),
      trailing: Text('Rs $price'),
    ),
  );
}
void main() => runApp(const MaterialApp(home: Scaffold(
  body: Column(children: [
    SizedBox(height: 24),
    ShopCard('Albert Ekka Chowk Sweets', 'Rasgulla 1 kg', 320),
    ShopCard('Kanke Road Tea Stall', 'Kulhad chai', 15),
    ShopCard('Firayalal Chowk Snacks', 'Samosa plate', 30),
  ]),
)));
Try it yourself: Add a fourth shop: Morabadi Fruit Mart, Apple 1 kg, 180.
Copy one ShopCard line and change the three values.
EASYReal project: fixing the most common beginner layout bugExample 4 of 10

Why does my Container fill the screen?

A Container with no child and no size takes all the space it is given. The Scaffold body gives tight constraints. Putting the Container in a Center makes the constraints loose.
void main() {
  runApp(MaterialApp(home: Scaffold(
    body: Column(children: [
      Expanded(child: Container(color: Colors.red.shade200,
          child: const Center(child: Text('A: no size, fills its area')))),
      Expanded(child: Center(child: Container(
          width: 160, height: 80, color: Colors.green.shade400,
          child: const Center(child: Text('B: 160 x 80'))))),
    ]),
  )));
}
Try it yourself: Make box B wider: 260.
Change width: 160 to 260.
EASYReal project: responsive text, brand coloursExample 5 of 10

Theme and screen size from context

Never hard-code a colour or screen size when Flutter can tell you. Theme.of(context) and MediaQuery.of(context) read values from the nearest parents.
class Banner1 extends StatelessWidget {
  const Banner1({super.key});
  @override
  Widget build(BuildContext context) {
    final w = MediaQuery.of(context).size.width;
    return Container(
      width: w * 0.8, padding: const EdgeInsets.all(16),
      color: Theme.of(context).colorScheme.primaryContainer,
      child: Text('80% of ${w.toInt()} pixels',
          style: Theme.of(context).textTheme.titleLarge),
    );
  }
}
void main() => runApp(MaterialApp(
  theme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepOrange)),
  home: const Scaffold(body: Center(child: Banner1())),
));
Try it yourself: Change the seed colour to Colors.teal.
Edit seedColor in ThemeData.
MEDIUMReal project: learning to size boxes correctlyExample 6 of 10

Constraints playground

A slider changes the maxWidth of a ConstrainedBox. The child asks for 300 pixels but cannot go beyond the limit. This is "constraints go down" in action.
class Play extends StatefulWidget {
  const Play({super.key});
  @override
  State<Play> createState() => _PlayState();
}
class _PlayState extends State<Play> {
  double maxW = 200;
  @override
  Widget build(BuildContext context) => Scaffold(
    body: Column(children: [
      Slider(value: maxW, min: 50, max: 340, onChanged: (v) => setState(() => maxW = v)),
      Text('maxWidth = ${maxW.toInt()}'),
      const SizedBox(height: 16),
      ConstrainedBox(
        constraints: BoxConstraints(maxWidth: maxW),
        child: Container(width: 300, height: 70, color: Colors.indigo,
            child: const Center(child: Text('I want 300', style: TextStyle(color: Colors.white)))),
      ),
    ]),
  );
}
void main() => runApp(const MaterialApp(home: Play()));
Try it yourself: Add minWidth: 120 to the BoxConstraints.
BoxConstraints(minWidth: 120, maxWidth: maxW).
MEDIUMReal project: sortable lists, reorderable cardsExample 7 of 10

Keys keep state with the right item

Each tile has its own counter (state). After Reverse the counters follow the names because every tile has a ValueKey. Remove the key and watch the counts stay in place while names move.
class Tile extends StatefulWidget {
  final String label;
  const Tile(this.label, {super.key});
  @override
  State<Tile> createState() => _TileState();
}
class _TileState extends State<Tile> {
  int n = 0;
  @override
  Widget build(BuildContext context) => ListTile(
    title: Text('${widget.label}: $n taps'),
    onTap: () => setState(() => n++),
  );
}
class Page extends StatefulWidget {
  const Page({super.key});
  @override
  State<Page> createState() => _PageState();
}
class _PageState extends State<Page> {
  List<String> names = ['Dhuska', 'Litti', 'Thekua'];
  @override
  Widget build(BuildContext context) => Scaffold(
    body: Column(children: [
      for (final s in names) Tile(s, key: ValueKey(s)),
      ElevatedButton(onPressed: () => setState(() => names = names.reversed.toList()), child: const Text('Reverse')),
    ]),
  );
}
void main() => runApp(const MaterialApp(home: Page()));
Try it yourself: Tap Dhuska twice, press Reverse, and check that the 2 moves with Dhuska. Then remove key: ValueKey(s).
Delete the key argument and run again.
MEDIUMReal project: responsive widgetsExample 8 of 10

LayoutBuilder shows the constraints

LayoutBuilder hands you the constraints given by the parent. You can print them or switch layouts. A slider resizes the parent here.
class Page extends StatefulWidget {
  const Page({super.key});
  @override
  State<Page> createState() => _PageState();
}
class _PageState extends State<Page> {
  double w = 300;
  @override
  Widget build(BuildContext context) => Scaffold(
    body: Column(children: [
      Slider(value: w, min: 120, max: 340, onChanged: (v) => setState(() => w = v)),
      SizedBox(
        width: w, height: 120,
        child: LayoutBuilder(builder: (context, box) {
          final wide = box.maxWidth > 220;
          return Container(
            color: wide ? Colors.teal.shade200 : Colors.orange.shade200,
            child: Center(child: Text(wide ? 'Wide layout\n${box.maxWidth.toInt()} px' : 'Narrow\n${box.maxWidth.toInt()} px', textAlign: TextAlign.center)),
          );
        }),
      ),
    ]),
  );
}
void main() => runApp(const MaterialApp(home: Page()));
Try it yourself: Add a third colour for width above 300.
Use else if (box.maxWidth > 300).
HARDReal project: category menus, comment threads, folder viewsExample 9 of 10

Recursive widget: district tree

A widget can build itself for its children. This recursion draws any depth of nesting: state, district, block. The tree in the code is the same tree Flutter builds on screen.
class Node {
  final String name;
  final List<Node> kids;
  const Node(this.name, [this.kids = const []]);
}
class TreeRow extends StatelessWidget {
  final Node node;
  final int depth;
  const TreeRow(this.node, this.depth, {super.key});
  @override
  Widget build(BuildContext context) => Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: [
      Padding(
        padding: EdgeInsets.only(left: 16.0 * depth, top: 4, bottom: 4),
        child: Row(children: [
          Icon(node.kids.isEmpty ? Icons.circle : Icons.folder, size: node.kids.isEmpty ? 10 : 20, color: Colors.teal),
          const SizedBox(width: 8),
          Text(node.name),
        ]),
      ),
      for (final k in node.kids) TreeRow(k, depth + 1),
    ],
  );
}
void main() {
  const root = Node('Jharkhand', [
    Node('Ranchi', [Node('Kanke'), Node('Namkum'), Node('Bundu')]),
    Node('Hazaribagh', [Node('Barhi'), Node('Ichak')]),
    Node('Dhanbad', [Node('Jharia')]),
  ]);
  runApp(const MaterialApp(home: Scaffold(body: Padding(padding: EdgeInsets.all(16), child: TreeRow(root, 0)))));
}
Try it yourself: Add the district Bokaro with the block Chas.
Add Node('Bokaro', [Node('Chas')]) to the root list.
HARDReal project: admin dashboards in school and business appsExample 10 of 10

School dashboard from small widgets

One big build() becomes hard to read. Split the screen into small widgets: StatTile and SectionTitle. Each is easy to test and reuse. This is how real apps stay maintainable.
class StatTile extends StatelessWidget {
  final String label, value;
  final IconData icon;
  final Color color;
  const StatTile(this.label, this.value, this.icon, this.color, {super.key});
  @override
  Widget build(BuildContext context) => Container(
    width: 150, padding: const EdgeInsets.all(14),
    decoration: BoxDecoration(color: color.withOpacity(0.12), borderRadius: BorderRadius.circular(14)),
    child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      Icon(icon, color: color),
      const SizedBox(height: 8),
      Text(value, style: const TextStyle(fontSize: 26, fontWeight: FontWeight.bold)),
      Text(label),
    ]),
  );
}
class SectionTitle extends StatelessWidget {
  final String text;
  const SectionTitle(this.text, {super.key});
  @override
  Widget build(BuildContext context) => Padding(
    padding: const EdgeInsets.fromLTRB(16, 20, 16, 8),
    child: Text(text, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w600)),
  );
}
class Dash extends StatelessWidget {
  const Dash({super.key});
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('DAV School Kanke')),
    body: ListView(children: const [
      SectionTitle('Today'),
      Padding(padding: EdgeInsets.symmetric(horizontal: 16), child: Wrap(spacing: 12, runSpacing: 12, children: [
        StatTile('Present', '412', Icons.people, Colors.green),
        StatTile('Absent', '38', Icons.person_off, Colors.red),
        StatTile('Fee due', 'Rs 1.2 L', Icons.currency_rupee, Colors.orange),
        StatTile('Teachers', '27', Icons.school, Colors.blue),
      ])),
      SectionTitle('Notices'),
      ListTile(leading: Icon(Icons.campaign), title: Text('Chhath holidays from 6 Nov')),
    ]),
  );
}
void main() => runApp(const MaterialApp(home: Dash()));
Try it yourself: Add a StatTile for "Buses" with value 9 and the Icons.directions_bus icon.
Add one more StatTile line inside Wrap.

Quick quiz

3 questions. Click an answer.
What is the main idea of Flutter UI?
Every screen is one big imageEverything is a widget in a treeOnly Text widgets existScreens use HTML
"Constraints go down, sizes go up" means:
The child sets the parent sizeThe parent gives limits, the child picks a size inside themSizes are randomOnly Container has constraints
When do you need a ValueKey?
For every TextWhen items with state can be reorderedNeverOnly in main()
Score: 0 / 3

Recap: what you learned in Module 21

Widget tree

Every screen is widgets inside widgets.

Custom widgets

A StatelessWidget class is reusable and tidy.

Constraints

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

Tight vs loose

Tight has no choice; loose allows 0 to max.

BuildContext

Look up Theme and MediaQuery from the tree.

Keys

ValueKey keeps state with the right item.

Next: Text and Typography - Make every word look right
MODULE 22 · PART 1

Text and Typography

Make every word look right
You will learn
  • Style text with TextStyle: size, weight, colour, spacing
  • Mix styles in one sentence with Text.rich and TextSpan
  • Use the Material type scale through textTheme
  • Control overflow with maxLines and ellipsis
  • Build tappable links and highlighted search results
You will build: a price tag, a news card and a search highlighter
4 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
🔠

Where is this used in real apps?

Most of an app is text: prices, names, headlines, buttons. Good typography is what makes an app look professional and easy to read.

TextStyle

Size, weight, colour, spacing and decoration of the text.

Text.rich

Bold, colour and links inside one sentence, such as "Rs 349 (MRP 499)".

Type scale

A small set of ready sizes so every screen uses the same look.

Ranchi Samachar
📰
Metro work starts near Kanke Road
City
Today
🏏
Ranchi wins state cricket final
Sports
2 h
🌧
Light rain expected on Sunday
Weather
5 h

Text and TextStyle

Text shows words. TextStyle decides how they look. Every property is optional.

Tip: keep sizes in a short list (12, 14, 16, 20, 28, 34). Too many different sizes make an app look messy.
void main() {
  runApp(const MaterialApp(home: Scaffold(
    body: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
      Text('Sharma Sweets', style: TextStyle(fontSize: 34, fontWeight: FontWeight.w800, color: Colors.deepOrange)),
      Text('Since 1985, Main Road Ranchi', style: TextStyle(fontSize: 16, letterSpacing: 2, color: Colors.grey)),
      SizedBox(height: 12),
      Text('Rs 499', style: TextStyle(fontSize: 20, decoration: TextDecoration.lineThrough, color: Colors.grey)),
      Text('Rs 349', style: TextStyle(fontSize: 28, fontWeight: FontWeight.bold, color: Colors.green)),
    ])),
  )));
}

Text.rich: many styles in one line

A TextSpan is a piece of text with its own style. Put several spans inside Text.rich and they flow as one paragraph.

Note: spans inherit the style of their parent span, so you only write what changes.
void main() {
  runApp(const MaterialApp(home: Scaffold(
    body: Padding(
      padding: EdgeInsets.all(20),
      child: Center(
        child: Text.rich(TextSpan(
          style: TextStyle(fontSize: 22),
          children: [
            TextSpan(text: 'Order '),
            TextSpan(text: '#1042', style: TextStyle(fontWeight: FontWeight.bold)),
            TextSpan(text: ' will reach '),
            TextSpan(text: 'Kanke Road', style: TextStyle(color: Colors.blue)),
            TextSpan(text: ' by '),
            TextSpan(text: '6:30 PM', style: TextStyle(color: Colors.red, fontWeight: FontWeight.w700)),
          ],
        )),
      ),
    ),
  )));
}

The type scale (textTheme)

Material gives you named styles. Using them keeps every screen consistent and lets the user change the system font size.

Best habit: write Theme.of(context).textTheme.titleLarge instead of a fixed fontSize. Your whole app can then change its look in one place.
class Scale extends StatelessWidget {
  const Scale({super.key});
  @override
  Widget build(BuildContext context) {
    final t = Theme.of(context).textTheme;
    return Padding(padding: const EdgeInsets.all(16), child: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('headlineMedium', style: t.headlineMedium),
        Text('titleLarge', style: t.titleLarge),
        Text('titleMedium', style: t.titleMedium),
        Text('bodyLarge: normal reading text', style: t.bodyLarge),
        Text('bodyMedium: default text', style: t.bodyMedium),
        Text('labelSmall: caption', style: t.labelSmall),
      ],
    ));
  }
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Scale())));

Long text: overflow, maxLines, softWrap

Phones are narrow. Decide what happens when text does not fit.

Yellow-black stripes in a real app mean a RenderFlex overflow. Fix it with Expanded, Flexible or maxLines.
void main() {
  const long = 'Ranchi Municipal Corporation has started a clean city drive across all 53 wards from Monday.';
  runApp(const MaterialApp(home: Scaffold(
    body: Padding(padding: EdgeInsets.all(16), child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      Text(long, maxLines: 1, overflow: TextOverflow.ellipsis),
      SizedBox(height: 12),
      Text(long, maxLines: 2, overflow: TextOverflow.ellipsis),
      SizedBox(height: 12),
      Text(long, textAlign: TextAlign.center),
    ])),
  )));
}

Fonts and pubspec

Flutter ships with Roboto on Android. For your own font, add the .ttf file in an assets/fonts folder, list it in pubspec.yaml, then use fontFamily. The package google_fonts loads hundreds of free fonts.

Honest note: the in-browser engine in these slides always draws with its default font. Font files and google_fonts need a real Flutter project.
# pubspec.yaml
flutter:
  fonts:
    - family: Poppins
      fonts:
        - asset: assets/fonts/Poppins-Regular.ttf
        - asset: assets/fonts/Poppins-Bold.ttf
          weight: 700

// Dart
Text('Namaste', style: TextStyle(fontFamily: 'Poppins', fontSize: 28));

Animated explainer: The type scale from big to small

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

Animated explainer: What happens when text is too long?

Press Next to walk through it step by step, or Auto play.
EASYReal project: shop and brand headersExample 1 of 10

Shop banner

Size, weight, colour and letter spacing are enough to build a clean banner. No images needed.
void main() {
  runApp(const MaterialApp(home: Scaffold(
    body: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
      Text('RANCHI BOOK HOUSE', style: TextStyle(fontSize: 30, fontWeight: FontWeight.w900, letterSpacing: 3, color: Color(0xFF0B3D91))),
      Text('Books  |  Stationery  |  Gifts', style: TextStyle(fontSize: 16, color: Colors.grey)),
      SizedBox(height: 20),
      Text('Open 9 AM to 9 PM', style: TextStyle(fontSize: 18, color: Colors.green, fontWeight: FontWeight.w600)),
    ])),
  )));
}
Try it yourself: Change the shop name and add a line with the phone number.
Add another Text widget in the Column.
EASYReal project: offer price on e-commerce cardsExample 2 of 10

Price with old price

A line-through old price and a bold new price show the discount at a glance.
void main() {
  runApp(const MaterialApp(home: Scaffold(
    body: Center(child: Row(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.end, children: [
      Text('Rs 899', style: TextStyle(fontSize: 18, color: Colors.grey, decoration: TextDecoration.lineThrough)),
      SizedBox(width: 10),
      Text('Rs 599', style: TextStyle(fontSize: 34, fontWeight: FontWeight.bold, color: Colors.green)),
      SizedBox(width: 10),
      Text('33% off', style: TextStyle(fontSize: 16, color: Colors.red, fontWeight: FontWeight.w600)),
    ])),
  )));
}
Try it yourself: Make the discount text orange.
Use Colors.orange.
EASYReal project: news feed, blog listExample 3 of 10

Headline in a news card

maxLines plus ellipsis keep every card the same height, even when headlines differ in length.
void main() {
  runApp(MaterialApp(home: Scaffold(
    body: Padding(padding: const EdgeInsets.all(16), child: Card(child: Padding(padding: const EdgeInsets.all(16), child: Column(crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: const [
      Text('Jharkhand Foundation Day celebrations begin at Morabadi Ground with cultural programmes from all districts',
          maxLines: 2, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
      SizedBox(height: 8),
      Text('Ranchi Samachar  -  2 hours ago', style: TextStyle(fontSize: 13, color: Colors.grey)),
    ])))),
  )));
}
Try it yourself: Change maxLines to 3 and see the difference.
Edit maxLines: 2.
EASYReal project: consistent screens in any appExample 4 of 10

Type scale screen

Instead of guessing sizes, use the named styles from the theme. Change the theme once and every Text updates.
void main() {
  runApp(MaterialApp(home: Builder(builder: (context) {
    final t = Theme.of(context).textTheme;
    return Scaffold(body: Padding(padding: const EdgeInsets.all(20), child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      Text('My Orders', style: t.headlineMedium),
      const SizedBox(height: 8),
      Text('Order #1042', style: t.titleMedium),
      Text('2 items delivered to Hinoo, Ranchi', style: t.bodyMedium),
      const SizedBox(height: 4),
      Text('Delivered on 18 Nov', style: t.labelSmall),
    ])));
  })));
}
Try it yourself: Use titleLarge for the order number.
Replace t.titleMedium with t.titleLarge.
EASYReal project: card with many texts of the same lookExample 5 of 10

DefaultTextStyle for a whole block

DefaultTextStyle sets a style once. Every Text below it inherits it, so you do not repeat yourself.
void main() {
  runApp(const MaterialApp(home: Scaffold(
    body: Center(child: DefaultTextStyle(
      style: TextStyle(fontSize: 22, color: Colors.indigo, fontWeight: FontWeight.w600),
      child: Column(mainAxisSize: MainAxisSize.min, children: [
        Text('Ranchi'),
        Text('Patna'),
        Text('Kolkata'),
        Text('Plain one', style: TextStyle(color: Colors.black, fontWeight: FontWeight.normal)),
      ]),
    )),
  )));
}
Try it yourself: Add Text("Gaya") to the column.
It automatically gets the same style.
MEDIUMReal project: settings: reading size in e-book and news appsExample 6 of 10

Font size slider (accessibility)

A slider changes fontSize in state. Many apps offer this because older readers like bigger text. The paragraph reflows without errors.
class Reader extends StatefulWidget {
  const Reader({super.key});
  @override
  State<Reader> createState() => _ReaderState();
}
class _ReaderState extends State<Reader> {
  double size = 16;
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Reader')),
    body: Padding(padding: const EdgeInsets.all(16), child: Column(children: [
      Row(children: [
        const Text('A', style: TextStyle(fontSize: 12)),
        Expanded(child: Slider(value: size, min: 12, max: 32, onChanged: (v) => setState(() => size = v))),
        const Text('A', style: TextStyle(fontSize: 26)),
      ]),
      Text('Betla National Park in Latehar district is famous for tigers, elephants and thick sal forests. Many families from Ranchi visit it in winter.',
          style: TextStyle(fontSize: size, height: 1.4)),
    ])),
  );
}
void main() => runApp(const MaterialApp(home: Reader()));
Try it yourself: Show the size as a number next to the slider.
Add Text(size.toInt().toString()).
MEDIUMReal project: offer banners, festival sale postersExample 7 of 10

Sale badge with spacing and shadow

letterSpacing, height and shadows give text a poster look. Combine them with a coloured Container.
void main() {
  runApp(MaterialApp(home: Scaffold(
    body: Center(child: Container(
      padding: const EdgeInsets.symmetric(horizontal: 28, vertical: 20),
      decoration: BoxDecoration(color: Colors.red.shade700, borderRadius: BorderRadius.circular(16)),
      child: const Column(mainAxisSize: MainAxisSize.min, children: [
        Text('DIWALI', style: TextStyle(color: Colors.white, fontSize: 40, fontWeight: FontWeight.w900, letterSpacing: 6,
            shadows: [Shadow(color: Colors.black54, blurRadius: 6, offset: Offset(2, 3))])),
        Text('SALE', style: TextStyle(color: Colors.amber, fontSize: 56, fontWeight: FontWeight.w900, height: 0.9)),
        SizedBox(height: 6),
        Text('Up to 50% off  -  Main Road Ranchi', style: TextStyle(color: Colors.white70, fontSize: 14)),
      ]),
    )),
  )));
}
Try it yourself: Change the festival to CHHATH and the colour to orange.
Edit the strings and Colors.orange.shade700.
MEDIUMReal project: sign-up screen: "I agree to Terms and Conditions"Example 8 of 10

Tappable terms link

A TextSpan can have a recognizer. Tapping the blue part runs your code, while the rest stays plain text.
class Terms extends StatefulWidget {
  const Terms({super.key});
  @override
  State<Terms> createState() => _TermsState();
}
class _TermsState extends State<Terms> {
  String msg = 'Tap a link';
  @override
  Widget build(BuildContext context) => Scaffold(
    body: Padding(padding: const EdgeInsets.all(24), child: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
      Text.rich(TextSpan(style: const TextStyle(fontSize: 18), children: [
        const TextSpan(text: 'I agree to the '),
        TextSpan(text: 'Terms', style: const TextStyle(color: Colors.blue, decoration: TextDecoration.underline),
            recognizer: TapGestureRecognizer()..onTap = () => setState(() => msg = 'Opening Terms page')),
        const TextSpan(text: ' and '),
        TextSpan(text: 'Privacy Policy', style: const TextStyle(color: Colors.blue, decoration: TextDecoration.underline),
            recognizer: TapGestureRecognizer()..onTap = () => setState(() => msg = 'Opening Privacy page')),
      ])),
      const SizedBox(height: 20),
      Text(msg),
    ]))),
  );
}
void main() => runApp(const MaterialApp(home: Terms()));
Try it yourself: Add a third link: Refund Policy.
Add one more TextSpan with its own recognizer.
HARDReal project: bill, receipt, cart linesExample 9 of 10

Invoice line with safe layout

Long item names must never push the price off screen. Expanded gives the name the leftover width and ellipsis trims it. The price keeps its own space on the right.
class Line extends StatelessWidget {
  final String name; final int qty; final double price;
  const Line(this.name, this.qty, this.price, {super.key});
  @override
  Widget build(BuildContext context) => Padding(
    padding: const EdgeInsets.symmetric(vertical: 6),
    child: Row(children: [
      Text('$qty x ', style: const TextStyle(color: Colors.grey)),
      Expanded(child: Text(name, maxLines: 1, overflow: TextOverflow.ellipsis)),
      const SizedBox(width: 8),
      Text('Rs ${(qty * price).toStringAsFixed(2)}', style: const TextStyle(fontWeight: FontWeight.bold)),
    ]),
  );
}
void main() => runApp(const MaterialApp(home: Scaffold(
  body: Padding(padding: EdgeInsets.all(20), child: Column(children: [
    Text('Bill - Kanke Road Kirana', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
    Divider(),
    Line('Basmati rice premium long grain 5 kg bag', 1, 640),
    Line('Mustard oil 1 L', 2, 165.5),
    Line('Sugar', 3, 46),
    Divider(),
    Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [Text('Total'), Text('Rs 1109.00', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18))]),
  ])),
)));
Try it yourself: Add a line "Tata salt 1 kg" 2 x 28.
Add Line('Tata salt 1 kg', 2, 28) and update the total.
HARDReal project: search results in contact, product and chat appsExample 10 of 10

Highlight the search word

Split the title around the search word and build TextSpans: normal, highlighted, normal. The result updates on every key press.
class Search extends StatefulWidget {
  const Search({super.key});
  @override
  State<Search> createState() => _SearchState();
}
class _SearchState extends State<Search> {
  String q = 'ra';
  final items = ['Ranchi', 'Patna', 'Raipur', 'Gaya', 'Dhanbad', 'Muzaffarpur', 'Bhagalpur'];
  Widget hl(String t) {
    final i = q.isEmpty ? -1 : t.toLowerCase().indexOf(q.toLowerCase());
    if (i < 0) return Text(t);
    return Text.rich(TextSpan(children: [
      TextSpan(text: t.substring(0, i)),
      TextSpan(text: t.substring(i, i + q.length), style: TextStyle(backgroundColor: Colors.yellow.shade300, fontWeight: FontWeight.bold)),
      TextSpan(text: t.substring(i + q.length)),
    ]));
  }
  @override
  Widget build(BuildContext context) => Scaffold(
    body: Padding(padding: const EdgeInsets.all(16), child: Column(children: [
      TextField(decoration: const InputDecoration(labelText: 'Search city', border: OutlineInputBorder()), onChanged: (v) => setState(() => q = v)),
      const SizedBox(height: 12),
      for (final c in items) if (c.toLowerCase().contains(q.toLowerCase())) ListTile(title: hl(c)),
    ])),
  );
}
void main() => runApp(const MaterialApp(home: Search()));
Try it yourself: Make the highlight colour light green.
Use Colors.lightGreen.shade200.

Quick quiz

3 questions. Click an answer.
Which widget lets you use several styles inside one sentence?
Text.rich with TextSpanRow onlyContainerPadding
Which setting adds "..." at the end of long text?
TextOverflow.fadeTextOverflow.ellipsissoftWrapTextAlign.end
Why use Theme.of(context).textTheme?
It is fasterEvery screen stays consistent and easy to changeIt adds animationIt is needed for Text
Score: 0 / 3

Recap: what you learned in Module 22

TextStyle

Size, weight, colour, spacing, decoration.

Text.rich

Many styles in one paragraph.

Type scale

Use textTheme for consistent screens.

Overflow

maxLines and ellipsis protect layouts.

Links

TextSpan recognizer makes tappable words.

Highlight

Split text into spans to mark search matches.

Next: Containers and Decoration - Cards, gradients, shadows and shapes
MODULE 23 · PART 1

Containers and Decoration

Cards, gradients, shadows and shapes
You will learn
  • Understand the Container box: margin, border, padding, content
  • Decorate boxes with colour, borders, radius, shadows and gradients
  • Cut shapes with ClipRRect, ClipOval and ClipPath
  • Fade, tilt and scale widgets with Opacity and Transform
  • Keep pictures in shape with AspectRatio and FittedBox
You will build: product cards, banners and a profile header
5 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
🎨

Where is this used in real apps?

Cards, buttons, banners, chat bubbles and avatars are all decorated boxes. Learn the box once and you can draw almost any modern screen.

Container

One widget with size, padding, margin and decoration.

BoxDecoration

Colour, rounded corners, border, shadow, gradient.

Clip widgets

Cut a child into a circle, rounded rectangle or custom shape.

Fresh Mart Ranchi
🍎
Apples 1 kg
Rs 180
🥕
Tomato 1 kg
Rs 40
🥦
Carrot 1 kg
Rs 50
🍋
Banana dozen
Rs 60

The Container box

A Container draws a box. From outside to inside: margin (space around), border, padding (space inside) and the child.

Rule: if you give Container a decoration, put the colour inside the decoration. Using both color and decoration causes an error.
void main() {
  runApp(MaterialApp(home: Scaffold(
    body: Center(
      child: Container(
        margin: const EdgeInsets.all(24),       // outside space
        padding: const EdgeInsets.all(20),      // inside space
        width: 240,
        decoration: BoxDecoration(
          color: Colors.amber.shade100,
          border: Border.all(color: Colors.orange, width: 3),
          borderRadius: BorderRadius.circular(16),
        ),
        child: const Text('Chhath Puja special thali', style: TextStyle(fontSize: 20)),
      ),
    ),
  )));
}

BoxDecoration: shadow, gradient, shape

Decoration is where Container becomes beautiful. Shadows lift a card off the page, gradients blend two colours, and BoxShape.circle makes a round box.

Soft shadows look better: low opacity (black26), large blur (10 to 20) and a small downward offset.
void main() {
  runApp(MaterialApp(home: Scaffold(
    body: Center(child: Row(mainAxisSize: MainAxisSize.min, children: [
      Container(
        width: 110, height: 110,
        decoration: BoxDecoration(
          color: Colors.white, borderRadius: BorderRadius.circular(18),
          boxShadow: [BoxShadow(color: Colors.black26, blurRadius: 12, offset: const Offset(0, 6))],
        ),
        child: const Center(child: Text('Shadow')),
      ),
      const SizedBox(width: 20),
      Container(
        width: 110, height: 110,
        decoration: const BoxDecoration(
          gradient: LinearGradient(colors: [Colors.deepOrange, Colors.amber]),
          shape: BoxShape.circle,
        ),
        child: const Center(child: Text('Gradient', style: TextStyle(color: Colors.white))),
      ),
    ])),
  )));
}

Clipping: make shapes

Clip widgets cut their child.

Images: wrap Image.network in ClipRRect to get rounded photos. The same idea works for any child.
void main() {
  runApp(MaterialApp(home: Scaffold(
    body: Center(child: Row(mainAxisSize: MainAxisSize.min, children: [
      ClipRRect(
        borderRadius: BorderRadius.circular(20),
        child: Container(width: 100, height: 100, color: Colors.teal),
      ),
      const SizedBox(width: 20),
      ClipOval(child: Container(width: 100, height: 100, color: Colors.purple)),
    ])),
  )));
}

Opacity, Transform and AspectRatio

Opacity fades a child. Transform.rotate / scale tilts or zooms it (layout space does not change). AspectRatio keeps width : height fixed, such as 16 : 9 for videos.

Honest note: Transform changes only how the child is painted. The space it takes in the layout stays the same as before.
void main() {
  runApp(MaterialApp(home: Scaffold(
    body: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
      Opacity(opacity: 0.4, child: Container(width: 120, height: 50, color: Colors.red)),
      const SizedBox(height: 20),
      Transform.rotate(angle: 0.2, child: Container(width: 120, height: 50, color: Colors.blue)),
      const SizedBox(height: 20),
      SizedBox(width: 200, child: AspectRatio(aspectRatio: 16 / 9, child: Container(color: Colors.green))),
    ])),
  )));
}

Animated explainer: Anatomy of a Container

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

Animated explainer: How a card is built, layer by layer

Press Next to walk through it step by step, or Auto play.
EASYReal project: filter chips on shopping appsExample 1 of 10

Category chip

A small Container with padding, colour and rounded corners is the base of every chip and tag.
void main() {
  runApp(const MaterialApp(home: Scaffold(
    body: Center(child: Row(mainAxisSize: MainAxisSize.min, children: [
      Chip1('Sweets', Colors.orange),
      SizedBox(width: 10),
      Chip1('Snacks', Colors.green),
      SizedBox(width: 10),
      Chip1('Drinks', Colors.blue),
    ])),
  )));
}
class Chip1 extends StatelessWidget {
  final String label; final MaterialColor color;
  const Chip1(this.label, this.color, {super.key});
  @override
  Widget build(BuildContext context) => Container(
    padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
    decoration: BoxDecoration(color: color.shade100, borderRadius: BorderRadius.circular(20)),
    child: Text(label, style: TextStyle(color: color.shade900, fontWeight: FontWeight.w600)),
  );
}
Try it yourself: Add a chip called Fruits in purple.
Add Chip1('Fruits', Colors.purple) in the Row.
EASYReal project: e-commerce product tileExample 2 of 10

Product card with shadow

White box + rounded corners + soft shadow = the classic card look. Padding keeps the text away from the edges.
void main() {
  runApp(MaterialApp(home: Scaffold(
    backgroundColor: Colors.grey.shade100,
    body: Center(child: Container(
      width: 220, padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white, borderRadius: BorderRadius.circular(16),
        boxShadow: const [BoxShadow(color: Colors.black12, blurRadius: 14, offset: Offset(0, 6))],
      ),
      child: const Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [
        Icon(Icons.shopping_bag, size: 48, color: Colors.deepOrange),
        SizedBox(height: 10),
        Text('Tussar Silk Saree', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
        Text('Bhagalpur weave', style: TextStyle(color: Colors.grey)),
        SizedBox(height: 8),
        Text('Rs 2,499', style: TextStyle(fontSize: 22, color: Colors.green, fontWeight: FontWeight.bold)),
      ]),
    )),
  )));
}
Try it yourself: Make the card width 260 and the corners 24.
Change width and BorderRadius.circular.
EASYReal project: user profile and chat listsExample 3 of 10

Circle avatar

BoxShape.circle turns a square Container into a circle. Initials work well when the user has no photo.
void main() {
  runApp(MaterialApp(home: Scaffold(
    body: Center(child: Row(mainAxisSize: MainAxisSize.min, children: [
      for (final n in ['AK', 'RS', 'MP']) Container(
        margin: const EdgeInsets.all(8), width: 64, height: 64,
        decoration: BoxDecoration(shape: BoxShape.circle, color: Colors.indigo.shade400,
            border: Border.all(color: Colors.white, width: 3),
            boxShadow: const [BoxShadow(color: Colors.black26, blurRadius: 6)]),
        child: Center(child: Text(n, style: const TextStyle(color: Colors.white, fontSize: 22, fontWeight: FontWeight.bold))),
      ),
    ])),
  )));
}
Try it yourself: Give each avatar a different colour.
Use a list of colours and index it.
EASYReal project: home-page offer bannerExample 4 of 10

Festival gradient banner

A LinearGradient with two colours gives a rich banner. No image needed, so it loads instantly.
void main() {
  runApp(MaterialApp(home: Scaffold(
    body: Padding(padding: const EdgeInsets.all(16), child: Container(
      height: 150, width: double.infinity, padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        gradient: const LinearGradient(colors: [Color(0xFFFF512F), Color(0xFFF09819)], begin: Alignment.topLeft, end: Alignment.bottomRight),
        borderRadius: BorderRadius.circular(20),
      ),
      child: const Column(crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [
        Text('Chhath Offer', style: TextStyle(color: Colors.white, fontSize: 28, fontWeight: FontWeight.w800)),
        Text('Flat 30% on pooja items', style: TextStyle(color: Colors.white70, fontSize: 16)),
      ]),
    )),
  )));
}
Try it yourself: Change the gradient to blue and purple.
Use Colors.blue and Colors.purple.
EASYReal project: WhatsApp-style chat screenExample 5 of 10

Chat bubble with one sharp corner

BorderRadius.only lets you round some corners and keep one square. That is the speech-bubble tail.
class Bubble extends StatelessWidget {
  final String text; final bool mine;
  const Bubble(this.text, this.mine, {super.key});
  @override
  Widget build(BuildContext context) => Align(
    alignment: mine ? Alignment.centerRight : Alignment.centerLeft,
    child: Container(
      margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
      padding: const EdgeInsets.all(12),
      constraints: const BoxConstraints(maxWidth: 240),
      decoration: BoxDecoration(
        color: mine ? Colors.green.shade200 : Colors.grey.shade300,
        borderRadius: BorderRadius.only(
          topLeft: const Radius.circular(16), topRight: const Radius.circular(16),
          bottomLeft: Radius.circular(mine ? 16 : 0), bottomRight: Radius.circular(mine ? 0 : 16)),
      ),
      child: Text(text),
    ),
  );
}
void main() => runApp(const MaterialApp(home: Scaffold(
  body: Column(children: [
    SizedBox(height: 30),
    Bubble('Namaste, is the Ranchi bus on time?', false),
    Bubble('Yes, it leaves Birsa Chowk at 6 PM.', true),
    Bubble('Thank you!', false),
  ]),
)));
Try it yourself: Add a reply from you: "Welcome".
Add Bubble('Welcome', true).
MEDIUMReal project: image viewer, sticker appsExample 6 of 10

Fade and tilt controls

Two sliders drive Opacity and Transform.rotate. State holds the numbers. The box keeps its place in the layout while it is painted tilted.
class Play extends StatefulWidget {
  const Play({super.key});
  @override
  State<Play> createState() => _PlayState();
}
class _PlayState extends State<Play> {
  double op = 1, ang = 0;
  @override
  Widget build(BuildContext context) => Scaffold(
    body: Column(children: [
      const SizedBox(height: 40),
      Opacity(opacity: op, child: Transform.rotate(angle: ang, child: Container(
        width: 150, height: 90,
        decoration: BoxDecoration(color: Colors.deepPurple, borderRadius: BorderRadius.circular(16)),
        child: const Center(child: Text('Sticker', style: TextStyle(color: Colors.white, fontSize: 24))),
      ))),
      const SizedBox(height: 40),
      Text('Opacity ${op.toStringAsFixed(2)}'),
      Slider(value: op, onChanged: (v) => setState(() => op = v)),
      Text('Angle ${ang.toStringAsFixed(2)} rad'),
      Slider(value: ang, min: -1, max: 1, onChanged: (v) => setState(() => ang = v)),
    ]),
  );
}
void main() => runApp(const MaterialApp(home: Play()));
Try it yourself: Add a third slider for Transform.scale.
Wrap the Container in Transform.scale(scale: sc).
MEDIUMReal project: video list in YouTube-style appsExample 7 of 10

Video thumbnail with AspectRatio

AspectRatio 16/9 keeps thumbnails the same shape on every phone. ClipRRect rounds the corners. A grey box stands in for the image.
class Thumb extends StatelessWidget {
  final String title; final Color c;
  const Thumb(this.title, this.c, {super.key});
  @override
  Widget build(BuildContext context) => Padding(
    padding: const EdgeInsets.all(12),
    child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      ClipRRect(
        borderRadius: BorderRadius.circular(12),
        child: AspectRatio(aspectRatio: 16 / 9, child: Container(color: c, child: const Center(child: Icon(Icons.play_circle, color: Colors.white, size: 48)))),
      ),
      const SizedBox(height: 6),
      Text(title, style: const TextStyle(fontWeight: FontWeight.w600)),
    ]),
  );
}
void main() => runApp(MaterialApp(home: Scaffold(
  body: ListView(children: [
    Thumb('Jonha Falls drone view', Colors.teal.shade400),
    Thumb('Ranchi street food tour', Colors.deepOrange.shade300),
  ]),
)));
Try it yourself: Change the aspect ratio to 4 / 3.
Edit aspectRatio: 4 / 3.
MEDIUMReal project: pricing plans and payment method choiceExample 8 of 10

Plan selector with highlighted border

Tapping a card stores its index in state. The selected card gets a thick coloured border. Same pattern as choosing UPI, card or cash.
class Plans extends StatefulWidget {
  const Plans({super.key});
  @override
  State<Plans> createState() => _PlansState();
}
class _PlansState extends State<Plans> {
  int sel = 1;
  final plans = const [['Basic', 'Rs 199 / month'], ['Standard', 'Rs 399 / month'], ['Premium', 'Rs 699 / month']];
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Choose plan')),
    body: Padding(padding: const EdgeInsets.all(16), child: Column(children: [
      for (var i = 0; i < plans.length; i++) GestureDetector(
        onTap: () => setState(() => sel = i),
        child: Container(
          width: double.infinity, margin: const EdgeInsets.only(bottom: 12), padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: sel == i ? Colors.indigo.shade50 : Colors.white,
            borderRadius: BorderRadius.circular(14),
            border: Border.all(color: sel == i ? Colors.indigo : Colors.grey.shade300, width: sel == i ? 3 : 1),
          ),
          child: Row(children: [
            Expanded(child: Text(plans[i][0], style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold))),
            Text(plans[i][1]),
          ]),
        ),
      ),
    ])),
  );
}
void main() => runApp(const MaterialApp(home: Plans()));
Try it yourself: Show a check icon on the selected card.
Add if (sel == i) const Icon(Icons.check_circle) inside the Row.
HARDReal project: profile and login screen headersExample 9 of 10

Wave header with ClipPath

ClipPath with a CustomClipper cuts a container along a curve you draw with a Path. Real apps use this for wave headers.
class Wave extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    final p = Path();
    p.lineTo(0, size.height - 40);
    p.quadraticBezierTo(size.width / 2, size.height + 20, size.width, size.height - 40);
    p.lineTo(size.width, 0);
    p.close();
    return p;
  }
  @override
  bool shouldReclip(CustomClipper<Path> old) => false;
}
void main() => runApp(MaterialApp(home: Scaffold(
  body: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
    ClipPath(
      clipper: Wave(),
      child: Container(
        height: 220, width: double.infinity,
        decoration: const BoxDecoration(gradient: LinearGradient(colors: [Colors.indigo, Colors.cyan])),
        padding: const EdgeInsets.fromLTRB(24, 70, 24, 0),
        child: const Text('Welcome back,\nAsha Kumari', style: TextStyle(color: Colors.white, fontSize: 28, fontWeight: FontWeight.bold)),
      ),
    ),
    const Padding(padding: EdgeInsets.all(24), child: Text('Ranchi University, BCA 3rd year')),
  ]),
)));
Try it yourself: Make the wave deeper by changing size.height + 20 to + 60.
Edit the quadraticBezierTo control point.
HARDReal project: social and team appsExample 10 of 10

Profile card with overlapping avatar

A Stack lets the avatar overlap the banner. Shadow, gradient, circle and clip are combined in one design, using only Container.
void main() {
  runApp(MaterialApp(home: Scaffold(
    backgroundColor: Colors.grey.shade200,
    body: Center(child: Container(
      width: 280,
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(20),
          boxShadow: const [BoxShadow(color: Colors.black26, blurRadius: 16, offset: Offset(0, 8))]),
      child: Column(mainAxisSize: MainAxisSize.min, children: [
        Stack(clipBehavior: Clip.none, alignment: Alignment.center, children: [
          ClipRRect(
            borderRadius: const BorderRadius.vertical(top: Radius.circular(20)),
            child: Container(height: 110, decoration: const BoxDecoration(gradient: LinearGradient(colors: [Color(0xFF0B6BFF), Color(0xFF8E5DE8)]))),
          ),
          Positioned(bottom: -36, child: Container(
            width: 80, height: 80,
            decoration: BoxDecoration(shape: BoxShape.circle, color: Colors.orange, border: Border.all(color: Colors.white, width: 4)),
            child: const Center(child: Text('NK', style: TextStyle(color: Colors.white, fontSize: 28, fontWeight: FontWeight.bold))),
          )),
        ]),
        const SizedBox(height: 46),
        const Text('Nandan Kumar', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
        const Text('Trainer, BrainBit Infotech Ranchi', style: TextStyle(color: Colors.grey)),
        const SizedBox(height: 16),
        const Row(mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [Text('5000+\nStudents', textAlign: TextAlign.center), Text('15+\nYears', textAlign: TextAlign.center)]),
        const SizedBox(height: 20),
      ]),
    )),
  )));
}
Try it yourself: Add a third stat: 100+ Projects.
Add Text('100+\nProjects', textAlign: TextAlign.center) to the Row.

Quick quiz

3 questions. Click an answer.
Where does the colour go if a Container has a decoration?
color: outside decorationInside BoxDecorationIn marginIn child
Which widget cuts a child into a circle?
ClipOvalOpacityPaddingAlign
What does padding do?
Space outside the boxSpace between the box edge and its childAdds a borderChanges colour
Score: 0 / 3

Recap: what you learned in Module 23

Container

margin, border, padding, child.

BoxDecoration

colour, radius, border, shadow, gradient.

Shapes

BoxShape.circle and BorderRadius.only.

Clip

ClipRRect, ClipOval, ClipPath cut children.

Opacity/Transform

Fade, tilt and scale.

AspectRatio

Keeps thumbnails in shape on every phone.

Next: Layout Widgets: Row, Column, Stack and more - Place everything exactly where you want
MODULE 24 · PART 1

Layout Widgets: Row, Column, Stack and more

Place everything exactly where you want
You will learn
  • Use Row and Column with main axis and cross axis alignment
  • Share space with Expanded, Flexible and Spacer
  • Overlap widgets with Stack, Positioned and Align
  • Flow tags onto new lines with Wrap
  • Find and fix overflow problems
You will build: an app bar, a ticket and a dashboard
5 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
📐

Where is this used in real apps?

Row and Column are used on every screen of every Flutter app. Stack puts a badge on a cart icon, and Wrap lays out tags that flow onto the next line.

Row / Column

Put widgets in a line: horizontal or vertical.

Expanded

Take all the space that is left, or a share of it.

Stack

Pile widgets on top of each other: badge, caption on image.

Bus Ticket
🚌
Ranchi to Patna
Seat 12A
Rs 650
🚌
Ranchi to Dhanbad
Seat 4B
Rs 280
🚌
Ranchi to Gaya
Seat 9C
Rs 420

Row and Column: main and cross axis

A Row goes left to right, so its main axis is horizontal. A Column goes top to bottom, so its main axis is vertical. The cross axis is the other direction.

Memory trick: main axis = the direction of the widget. Column: main is vertical. Row: main is horizontal.
void main() {
  runApp(const MaterialApp(home: Scaffold(
    body: Column(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Ranchi', style: TextStyle(fontSize: 30)),
        Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [Icon(Icons.home), Icon(Icons.star), Icon(Icons.settings)]),
        Text('Patna', style: TextStyle(fontSize: 30)),
      ],
    ),
  )));
}

Expanded, Flexible and Spacer

Inside a Row or Column, Expanded takes the leftover space. If two children are Expanded, they share it by their flex numbers. Spacer is an empty Expanded.

Expanded vs Flexible: Expanded forces the child to fill its share. Flexible lets the child be smaller if it wants.
void main() {
  runApp(const MaterialApp(home: Scaffold(
    body: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
      Row(children: [
        Expanded(flex: 1, child: ColoredBox(color: Colors.red, child: SizedBox(height: 50, child: Center(child: Text('1'))))),
        Expanded(flex: 2, child: ColoredBox(color: Colors.green, child: SizedBox(height: 50, child: Center(child: Text('2'))))),
        Expanded(flex: 1, child: ColoredBox(color: Colors.blue, child: SizedBox(height: 50, child: Center(child: Text('1'))))),
      ]),
      SizedBox(height: 20),
      Row(children: [Text('Left'), Spacer(), Text('Right')]),
    ])),
  )));
}

Stack, Positioned and Align

Stack places children on top of each other. The first child is at the bottom. Use Positioned (top, left, right, bottom) or Align to put a child in a corner.

Tip: a Stack is as big as its biggest non-positioned child. Positioned children can sit outside with clipBehavior: Clip.none.
void main() {
  runApp(MaterialApp(home: Scaffold(
    body: Center(child: Stack(children: [
      Container(width: 220, height: 140, decoration: BoxDecoration(color: Colors.teal, borderRadius: BorderRadius.circular(16))),
      const Positioned(top: 10, right: 10, child: Icon(Icons.favorite, color: Colors.white)),
      const Align(alignment: Alignment.bottomLeft, child: Padding(padding: EdgeInsets.all(12), child: Text('Betla National Park', style: TextStyle(color: Colors.white, fontSize: 18)))),
    ])),
  )));
}

Wrap and overflow fixes

Wrap works like a Row but moves extra items to the next line. When a Row or Column is too big for the screen Flutter shows yellow and black stripes. Fix it by using Expanded, Wrap, SingleChildScrollView or smaller content.

Overflow checklist: 1) Long text? Use Expanded and ellipsis. 2) Too many items? Use Wrap or ListView. 3) Whole screen too tall? Use SingleChildScrollView.
void main() {
  runApp(const MaterialApp(home: Scaffold(
    body: Padding(padding: EdgeInsets.all(16), child: Wrap(
      spacing: 8, runSpacing: 8,
      children: [
        Chip(label: Text('Ranchi')), Chip(label: Text('Jamshedpur')), Chip(label: Text('Dhanbad')),
        Chip(label: Text('Bokaro')), Chip(label: Text('Hazaribagh')), Chip(label: Text('Deoghar')),
      ],
    )),
  )));
}

Animated explainer: Main axis and cross axis

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

Animated explainer: How Expanded shares space

Press Next to walk through it step by step, or Auto play.
EASYReal project: custom top bar on any home screenExample 1 of 10

App bar with Row

A Row with spaceBetween puts the logo on the left and icons on the right.
void main() {
  runApp(const MaterialApp(home: Scaffold(
    body: SafeArea(child: Padding(padding: EdgeInsets.all(16), child: Column(children: [
      Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
        Text('Ranchi Kart', style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: Colors.deepOrange)),
        Row(children: [Icon(Icons.search), SizedBox(width: 16), Icon(Icons.shopping_cart)]),
      ]),
    ]))),
  )));
}
Try it yourself: Add a notification bell icon.
Add another Icon(Icons.notifications) in the inner Row.
EASYReal project: contact and address blocksExample 2 of 10

Contact card with Column

CrossAxisAlignment.start aligns all lines to the left. Without it, a Column centres its children.
void main() {
  runApp(const MaterialApp(home: Scaffold(
    body: Center(child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [
      Text('BrainBit Infotech', style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold)),
      SizedBox(height: 6),
      Text('Main Road, Ranchi, Jharkhand'),
      Text('Phone: 0651 000 0000'),
      Text('Open: Mon to Sat, 9 AM to 6 PM'),
    ])),
  )));
}
Try it yourself: Change to CrossAxisAlignment.end.
Edit crossAxisAlignment.
EASYReal project: dashboard stat stripExample 3 of 10

Three columns with Expanded

Three Expanded children share the width equally. No pixel maths needed, it works on every phone.
class Stat extends StatelessWidget {
  final String v, l; final Color c;
  const Stat(this.v, this.l, this.c, {super.key});
  @override
  Widget build(BuildContext context) => Expanded(child: Container(
    margin: const EdgeInsets.all(4), padding: const EdgeInsets.symmetric(vertical: 16),
    decoration: BoxDecoration(color: c.withOpacity(0.15), borderRadius: BorderRadius.circular(12)),
    child: Column(children: [Text(v, style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: c)), Text(l)]),
  ));
}
void main() => runApp(const MaterialApp(home: Scaffold(
  body: SafeArea(child: Padding(padding: EdgeInsets.all(12), child: Row(children: [
    Stat('120', 'Orders', Colors.blue), Stat('98', 'Delivered', Colors.green), Stat('22', 'Pending', Colors.orange),
  ]))),
)));
Try it yourself: Change the middle one to flex 2 by wrapping it in Expanded(flex: 2).
Move the Expanded out of Stat or add a flex parameter.
EASYReal project: list row with action at the rightExample 4 of 10

Spacer pushes a button to the end

Spacer fills the gap, so the second item sits at the far end whatever the screen width.
void main() {
  runApp(MaterialApp(home: Scaffold(
    body: Padding(padding: const EdgeInsets.all(16), child: Column(children: [
      Row(children: [
        const CircleAvatar(child: Text('A')),
        const SizedBox(width: 12),
        const Text('Asha Kumari', style: TextStyle(fontSize: 18)),
        const Spacer(),
        ElevatedButton(onPressed: () {}, child: const Text('Follow')),
      ]),
    ])),
  )));
}
Try it yourself: Add a second row for Ravi with a Message button.
Copy the whole Row and edit the texts.
EASYReal project: shopping cart, notification bellExample 5 of 10

Cart icon with a badge

A Stack overlays a small red circle on the icon. Positioned places it at the top-right corner.
class Cart extends StatelessWidget {
  final int count;
  const Cart(this.count, {super.key});
  @override
  Widget build(BuildContext context) => Stack(clipBehavior: Clip.none, children: [
    const Icon(Icons.shopping_cart, size: 48),
    Positioned(right: -6, top: -6, 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, fontWeight: FontWeight.bold)),
    )),
  ]);
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Center(child: Row(mainAxisSize: MainAxisSize.min, children: [Cart(3), SizedBox(width: 40), Cart(12)])))));
Try it yourself: Hide the badge when count is 0.
Wrap the Positioned in if (count > 0).
MEDIUMReal project: interest picker, filter tags, skill chipsExample 6 of 10

Tag selector with Wrap

Wrap flows tags onto new lines. A Set in state remembers which are chosen, and FilterChip shows the selection.
class Tags extends StatefulWidget {
  const Tags({super.key});
  @override
  State<Tags> createState() => _TagsState();
}
class _TagsState extends State<Tags> {
  final all = ['Cricket', 'Hockey', 'Football', 'Archery', 'Kabaddi', 'Chess', 'Badminton', 'Athletics'];
  final picked = <String>{'Hockey'};
  @override
  Widget build(BuildContext context) => Scaffold(
    body: Padding(padding: const EdgeInsets.all(16), child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      const Text('Pick your sports', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
      const SizedBox(height: 12),
      Wrap(spacing: 8, runSpacing: 4, children: [
        for (final t in all) FilterChip(
          label: Text(t), selected: picked.contains(t),
          onSelected: (v) => setState(() { if (v) { picked.add(t); } else { picked.remove(t); } }),
        ),
      ]),
      const SizedBox(height: 16),
      Text('Chosen: ${picked.length}'),
    ])),
  );
}
void main() => runApp(const MaterialApp(home: Tags()));
Try it yourself: Add the tag Volleyball.
Add it to the all list.
MEDIUMReal project: destination cards, news hero imageExample 7 of 10

Caption over an image area

Stack + Align places a dark caption strip at the bottom of a coloured area, the same layout used on image cards.
void main() {
  runApp(MaterialApp(home: Scaffold(
    body: Center(child: ClipRRect(
      borderRadius: BorderRadius.circular(18),
      child: SizedBox(width: 280, height: 180, child: Stack(children: [
        Container(decoration: const BoxDecoration(gradient: LinearGradient(colors: [Color(0xFF134E5E), Color(0xFF71B280)], begin: Alignment.topLeft, end: Alignment.bottomRight))),
        const Positioned(top: 12, left: 12, child: Chip(label: Text('Waterfall'))),
        Align(alignment: Alignment.bottomCenter, child: Container(
          width: double.infinity, padding: const EdgeInsets.all(12), color: Colors.black54,
          child: const Text('Hundru Falls, Ranchi', style: TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.w600)),
        )),
      ])),
    )),
  )));
}
Try it yourself: Move the caption to the top by using Alignment.topCenter.
Change the Align alignment.
MEDIUMReal project: pricing tables, comparison cardsExample 8 of 10

Equal-height cards with IntrinsicHeight

In a Row, cards with different text have different heights. IntrinsicHeight with CrossAxisAlignment.stretch makes them all as tall as the tallest.
class Plan extends StatelessWidget {
  final String name, desc; final Color c;
  const Plan(this.name, this.desc, this.c, {super.key});
  @override
  Widget build(BuildContext context) => Expanded(child: Container(
    margin: const EdgeInsets.all(4), padding: const EdgeInsets.all(10),
    decoration: BoxDecoration(color: c.withOpacity(0.18), borderRadius: BorderRadius.circular(12)),
    child: Column(children: [Text(name, style: const TextStyle(fontWeight: FontWeight.bold)), const SizedBox(height: 6), Text(desc, textAlign: TextAlign.center, style: const TextStyle(fontSize: 12))]),
  ));
}
void main() => runApp(const MaterialApp(home: Scaffold(
  body: Padding(padding: EdgeInsets.fromLTRB(8, 60, 8, 8), child: Column(children: [IntrinsicHeight(child: Row(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
    Plan('Basic', 'Notes', Colors.blue),
    Plan('Pro', 'Notes, live classes, doubt support and weekly tests', Colors.green),
    Plan('Max', 'Everything plus placement help', Colors.orange),
  ]))])),
)));
Try it yourself: Remove IntrinsicHeight and compare.
Delete the wrapper and run again.
HARDReal project: checkout screen on small phonesExample 9 of 10

Order summary that never overflows

Long names use Expanded + ellipsis, the whole page sits in a SingleChildScrollView and the total is pinned at the bottom with a Column and Spacer-like Expanded. It works on any screen height.
class Summary extends StatelessWidget {
  const Summary({super.key});
  @override
  Widget build(BuildContext context) {
    final items = [['Tussar silk saree with hand embroidery border', 2499], ['Dokra brass elephant figurine', 899], ['Sohrai painting small', 650], ['Lac bangles set of 12', 320], ['Bamboo basket large', 450], ['Mahua jam 250 g', 180]];
    int total = 0;
    for (final i in items) { total += i[1] as int; }
    return Scaffold(
      appBar: AppBar(title: const Text('Order summary')),
      body: Column(children: [
        Expanded(child: SingleChildScrollView(child: Column(children: [
          for (final i in items) ListTile(
            title: Text(i[0] as String, maxLines: 1, overflow: TextOverflow.ellipsis),
            trailing: Text('Rs ${i[1]}'),
          ),
        ]))),
        Container(
          padding: const EdgeInsets.all(16), color: Colors.grey.shade200,
          child: Row(children: [const Text('Total', style: TextStyle(fontSize: 18)), const Spacer(), Text('Rs $total', style: const TextStyle(fontSize: 22, fontWeight: FontWeight.bold))]),
        ),
      ]),
    );
  }
}
void main() => runApp(const MaterialApp(home: Summary()));
Try it yourself: Add 4 more items and check that the total stays at the bottom.
Add rows to the items list.
HARDReal project: ticket and boarding-pass screensExample 10 of 10

Bus ticket layout

A ticket combines everything: Row with Expanded for from and to, a dashed-style Divider, a Stack for the status stamp and a Wrap of details.
Widget col(String l, String v) => Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
  Text(l, style: const TextStyle(color: Colors.grey, fontSize: 12)), Text(v, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600))]);
void main() {
  runApp(MaterialApp(home: Scaffold(
    backgroundColor: Colors.blueGrey.shade50,
    body: Center(child: Container(
      width: 300, padding: const EdgeInsets.all(18),
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(18), boxShadow: const [BoxShadow(color: Colors.black12, blurRadius: 12)]),
      child: Stack(children: [
        Column(mainAxisSize: MainAxisSize.min, children: [
          Row(children: [
            Expanded(child: col('FROM', 'Ranchi')),
            const Icon(Icons.directions_bus, color: Colors.blue),
            Expanded(child: Align(alignment: Alignment.centerRight, child: col('TO', 'Patna'))),
          ]),
          const Divider(height: 28),
          Wrap(spacing: 28, runSpacing: 12, children: [col('DATE', '24 Nov'), col('TIME', '9:30 PM'), col('SEAT', '12A'), col('FARE', 'Rs 650')]),
        ]),
        const Positioned(right: 0, bottom: 0, child: Text('PAID', style: TextStyle(color: Colors.green, fontSize: 18, fontWeight: FontWeight.w900))),
      ]),
    )),
  )));
}
Try it yourself: Add a PASSENGER field with your name.
Add col('PASSENGER', 'Asha') to the Wrap.

Quick quiz

3 questions. Click an answer.
What does Expanded do inside a Row?
Adds a borderTakes the leftover spaceScrolls the RowHides the child
Which widget puts widgets on top of each other?
ColumnWrapStackSpacer
A Row of tags runs off the screen. Best fix?
Use WrapMake text smallerUse OpacityUse Container
Score: 0 / 3

Recap: what you learned in Module 24

Row / Column

Main axis and cross axis alignment.

Expanded

Shares leftover space by flex.

Spacer

An empty Expanded gap.

Stack

Overlap widgets with Positioned or Align.

Wrap

Tags flow to the next line.

Overflow

Expanded, Wrap or scroll fixes stripes.

Next: the next part of the course.

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