FLUTTER WIDGETS & DESIGN COURSE · BRAINBIT INFOTECH

Part 4

4 modules · 21 class hours · 40 practical examples

Module 33: Material 3, Themes and Dark Mode

One theme, the whole app changes · 5 h

Module 34: Responsive and Adaptive Design

One app, every screen size · 5 h

Module 35: Custom Painting, Clipping and Effects

Draw anything the widgets do not have · 5 h

Module 36: UI Design Practice and Capstone

Turn skills into polished screens and a portfolio · 6 h

MODULE 33 · PART 4

Material 3, Themes and Dark Mode

One theme, the whole app changes
You will learn
  • Create a colour scheme from one seed colour
  • Read colours and text styles with Theme.of(context)
  • Switch between light and dark mode
  • Style all buttons and cards in one place with component themes
  • Check contrast and text size for accessibility
You will build: a branded app with a colour scheme, dark mode switch and reusable component themes
5 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
🎨

Where is this used in real apps?

A shop app keeps its brand colour on every screen. Change one line and the whole app changes. Dark mode saves battery at night and many users switch it on.

ColorScheme

A set of matching colours made from one seed colour.

ThemeData

Colours, text styles and component styles for the whole app.

Dark mode

darkTheme plus themeMode. Use scheme colours, never hard-coded ones.

BrandShop
🛍
Kurta set
Rs 1,299
🛍
Sandals
Rs 599
🛍
Backpack
Rs 899

ColorScheme.fromSeed

Give fromSeed one colour. Flutter builds a full Material 3 palette: primary, secondary, surface, error and their matching on... colours for text on top.

Honest note: real Flutter builds the palette with the HCT colour science. The slide engine uses a close approximation, so exact shades differ slightly.
class Page extends StatelessWidget {
  const Page({super.key});
  Widget chip(String n, Color bg, Color fg) => Container(margin: const EdgeInsets.all(4), padding: const EdgeInsets.all(14), color: bg, child: Text(n, style: TextStyle(color: fg)));
  @override
  Widget build(BuildContext context) {
    final cs = Theme.of(context).colorScheme;
    return Scaffold(
      appBar: AppBar(title: const Text('Scheme')),
      body: Padding(padding: const EdgeInsets.all(12), child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        chip('primary / onPrimary', cs.primary, cs.onPrimary),
        chip('primaryContainer', cs.primaryContainer, cs.onPrimaryContainer),
        chip('secondary', cs.secondary, cs.onSecondary),
        chip('surface', cs.surfaceContainerHighest, cs.onSurface),
        chip('error', cs.error, cs.onError),
      ])),
    );
  }
}
void main() => runApp(MaterialApp(
  theme: ThemeData(useMaterial3: true, colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal)),
  home: const Page(),
));

Theme.of(context)

Never hard-code colours in screens. Ask the theme: Theme.of(context).colorScheme.primary and Theme.of(context).textTheme.titleLarge. When the theme changes, every screen follows.

Tip: copyWith changes only what you name and keeps the rest of the style.
class Page extends StatelessWidget {
  const Page({super.key});
  @override
  Widget build(BuildContext context) {
    final t = Theme.of(context);
    return Scaffold(
      body: Padding(padding: const EdgeInsets.all(20), child: Column(crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [
        Text('Headline', style: t.textTheme.headlineMedium),
        Text('Title large', style: t.textTheme.titleLarge),
        Text('Body medium for paragraphs', style: t.textTheme.bodyMedium),
        const SizedBox(height: 12),
        Text('Coloured with the theme', style: t.textTheme.titleMedium?.copyWith(color: t.colorScheme.primary)),
      ])),
    );
  }
}
void main() => runApp(MaterialApp(theme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepOrange)), home: const Page()));

Dark mode with themeMode

Give MaterialApp a theme, a darkTheme and a themeMode. ThemeMode.system follows the phone setting. Build screens with scheme colours and they adapt automatically.

Rule: the switch lives above MaterialApp (in a StatefulWidget) because MaterialApp reads themeMode.
class App extends StatefulWidget {
  const App({super.key});
  @override
  State<App> createState() => _AppState();
}
class _AppState extends State<App> {
  ThemeMode mode = ThemeMode.light;
  @override
  Widget build(BuildContext context) => MaterialApp(
    themeMode: mode,
    theme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.indigo)),
    darkTheme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.indigo, brightness: Brightness.dark)),
    home: Scaffold(
      appBar: AppBar(title: const Text('Dark mode')),
      body: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
        const Card(child: Padding(padding: EdgeInsets.all(24), child: Text('Hello from Ranchi'))),
        SwitchListTile(title: const Text('Dark mode'), value: mode == ThemeMode.dark, onChanged: (v) => setState(() => mode = v ? ThemeMode.dark : ThemeMode.light)),
      ])),
    ),
  );
}
void main() => runApp(const App());

Component themes

Instead of styling every button, set it once in ThemeData: elevatedButtonTheme, cardTheme, appBarTheme. A single button can still override the theme.

Honest note: the slide engine supports card, button, text and app bar themes. Others (like inputDecorationTheme) work in real Flutter but are not shown here.
void main() {
  runApp(MaterialApp(
    theme: ThemeData(
      colorScheme: ColorScheme.fromSeed(seedColor: Colors.green),
      cardTheme: CardTheme(color: Colors.amber.shade50, elevation: 3, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20))),
      elevatedButtonTheme: ElevatedButtonThemeData(style: ElevatedButton.styleFrom(backgroundColor: Colors.green.shade700, foregroundColor: Colors.white)),
    ),
    home: Scaffold(
      appBar: AppBar(title: const Text('Themed')),
      body: Padding(padding: const EdgeInsets.all(16), child: Column(children: [
        const Card(child: Padding(padding: EdgeInsets.all(24), child: Text('All cards look like this'))),
        const SizedBox(height: 12),
        ElevatedButton(onPressed: () {}, child: const Text('Themed button')),
        ElevatedButton(onPressed: () {}, style: ElevatedButton.styleFrom(backgroundColor: Colors.red, foregroundColor: Colors.white), child: const Text('Override')),
      ])),
    ),
  ));
}

Animated explainer: One seed, a whole palette

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

Animated explainer: Light and dark together

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

Pick a brand colour

Changing seedColor recolours the AppBar, buttons and FAB at once.
void main() {
  runApp(MaterialApp(
    theme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple)),
    home: Scaffold(
      appBar: AppBar(title: const Text('Brand colour')),
      body: Center(child: FilledButton(onPressed: () {}, child: const Text('Order now'))),
      floatingActionButton: FloatingActionButton(onPressed: () {}, child: const Icon(Icons.add)),
    ),
  ));
}
Try it yourself: Try Colors.orange, then Colors.teal.
Change seedColor only.
EASYReal project: design review and brand guide screensExample 2 of 10

Scheme colour swatches

Print each colour from colorScheme with its "on" partner so you see which pairs are safe for text.
class Page extends StatelessWidget {
  const Page({super.key});
  @override
  Widget build(BuildContext context) {
    final cs = Theme.of(context).colorScheme;
    final pairs = {'primary': [cs.primary, cs.onPrimary], 'secondary': [cs.secondary, cs.onSecondary], 'tertiary': [cs.tertiary, cs.onTertiary], 'error': [cs.error, cs.onError]};
    return Scaffold(body: ListView(padding: const EdgeInsets.all(16), children: [
      for (final e in pairs.entries) Container(height: 64, margin: const EdgeInsets.only(bottom: 8), alignment: Alignment.center, color: e.value[0], child: Text(e.key, style: TextStyle(color: e.value[1], fontSize: 18))),
    ]));
  }
}
void main() => runApp(MaterialApp(theme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue)), home: const Page()));
Try it yourself: Add surface and onSurface.
Add a map entry.
EASYReal project: consistent headings across screensExample 3 of 10

Text theme styles

Use the built-in sizes: displayLarge, headlineMedium, titleLarge, bodyMedium, labelSmall. Same style, same meaning, everywhere.
class Page extends StatelessWidget {
  const Page({super.key});
  @override
  Widget build(BuildContext context) {
    final t = Theme.of(context).textTheme;
    return Scaffold(body: Padding(padding: const EdgeInsets.all(20), child: Column(crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [
      Text('Display', style: t.displaySmall),
      Text('Headline', style: t.headlineMedium),
      Text('Title', style: t.titleLarge),
      Text('Body text for reading', style: t.bodyLarge),
      Text('LABEL SMALL', style: t.labelSmall),
    ])));
  }
}
void main() => runApp(const MaterialApp(home: Page()));
Try it yourself: Make Headline use the primary colour.
copyWith(color: ...) with Theme.of(context).colorScheme.primary.
EASYReal project: checking both themes while designingExample 4 of 10

Light and dark side by side

Theme widgets let two halves of one screen use different themes. Handy to compare light and dark.
Widget half(Brightness b) => Theme(
  data: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal, brightness: b)),
  child: Builder(builder: (context) => Container(
    color: Theme.of(context).colorScheme.surface, padding: const EdgeInsets.all(12),
    child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
      Text(b == Brightness.dark ? 'Dark' : 'Light', style: TextStyle(color: Theme.of(context).colorScheme.onSurface, fontSize: 22)),
      const SizedBox(height: 8),
      FilledButton(onPressed: () {}, child: const Text('Buy')),
    ]),
  )),
);
void main() {
  runApp(MaterialApp(home: Scaffold(body: Row(children: [Expanded(child: half(Brightness.light)), Expanded(child: half(Brightness.dark))]))));
}
Try it yourself: Change the seed to Colors.orange.
seedColor in half().
EASYReal project: brand button shapeExample 5 of 10

Rounded buttons for the whole app

filledButtonTheme sets the shape once. Every FilledButton in the app follows.
void main() {
  runApp(MaterialApp(
    theme: ThemeData(
      colorScheme: ColorScheme.fromSeed(seedColor: Colors.indigo),
      elevatedButtonTheme: ElevatedButtonThemeData(style: ElevatedButton.styleFrom(shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)), backgroundColor: Colors.indigo, foregroundColor: Colors.white)),
    ),
    home: Scaffold(body: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
      ElevatedButton(onPressed: () {}, child: const Text('Sharp button')),
      const SizedBox(height: 8),
      ElevatedButton(onPressed: () {}, child: const Text('Same style, no repeat')),
    ]))),
  ));
}
Try it yourself: Make the radius 30 for a pill shape.
BorderRadius.circular(30).
MEDIUMReal project: settings screen in any appExample 6 of 10

Dark mode switch

A StatefulWidget above MaterialApp holds the ThemeMode. A switch in settings flips it, and the whole app changes.
class App extends StatefulWidget {
  const App({super.key});
  @override
  State<App> createState() => _AppState();
}
class _AppState extends State<App> {
  bool dark = false;
  @override
  Widget build(BuildContext context) => MaterialApp(
    themeMode: dark ? ThemeMode.dark : ThemeMode.light,
    theme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.green)),
    darkTheme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.green, brightness: Brightness.dark)),
    home: Scaffold(
      appBar: AppBar(title: const Text('Settings')),
      body: ListView(children: [
        SwitchListTile(secondary: const Icon(Icons.dark_mode), title: const Text('Dark mode'), value: dark, onChanged: (v) => setState(() => dark = v)),
        const ListTile(leading: Icon(Icons.language), title: Text('Language'), subtitle: Text('English')),
        const ListTile(leading: Icon(Icons.notifications), title: Text('Notifications')),
      ]),
    ),
  );
}
void main() => runApp(const App());
Try it yourself: Add a text size setting.
Another state value, used in MediaQuery or textScaler.
MEDIUMReal project: brand typographyExample 7 of 10

Own text theme

TextTheme inside ThemeData changes the headline and body styles of the whole app.
void main() {
  runApp(MaterialApp(
    theme: ThemeData(
      colorScheme: ColorScheme.fromSeed(seedColor: Colors.brown),
      textTheme: const TextTheme(
        headlineMedium: TextStyle(fontSize: 34, fontWeight: FontWeight.w800, letterSpacing: 1),
        bodyMedium: TextStyle(fontSize: 18, height: 1.5),
      ),
    ),
    home: Builder(builder: (context) => Scaffold(
      body: Padding(padding: const EdgeInsets.all(24), child: Column(crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [
        Text('Kanke Road Tea', style: Theme.of(context).textTheme.headlineMedium),
        const SizedBox(height: 8),
        Text('Fresh Assam chai and biscuits, served hot since 1998.', style: Theme.of(context).textTheme.bodyMedium),
      ])),
    )),
  ));
}
Try it yourself: Make the body text 22.
bodyMedium fontSize.
MEDIUMReal project: success, warning and error messagesExample 8 of 10

Status colours that adapt

Pick colours from the scheme where possible. For custom ones (like success green) make a small helper that returns a different shade for dark mode.
Color success(BuildContext c) => Theme.of(c).brightness == Brightness.dark ? Colors.green.shade300 : Colors.green.shade800;
class Page extends StatelessWidget {
  const Page({super.key});
  @override
  Widget build(BuildContext context) {
    final cs = Theme.of(context).colorScheme;
    Widget msg(IconData i, String t, Color c) => Container(margin: const EdgeInsets.only(bottom: 10), padding: const EdgeInsets.all(14), decoration: BoxDecoration(color: c.withOpacity(0.12), borderRadius: BorderRadius.circular(10), border: Border.all(color: c)), child: Row(children: [Icon(i, color: c), const SizedBox(width: 10), Expanded(child: Text(t))]));
    return Scaffold(body: Padding(padding: const EdgeInsets.all(16), child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
      msg(Icons.check_circle, 'Payment received', success(context)),
      msg(Icons.error, 'Card declined', cs.error),
      msg(Icons.info, 'Delivery in 2 days', cs.primary),
    ])));
  }
}
void main() => runApp(MaterialApp(theme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue)), darkTheme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue, brightness: Brightness.dark)), themeMode: ThemeMode.dark, home: const Page()));
Try it yourself: Change themeMode to light and compare.
ThemeMode.light.
HARDReal project: white-label apps, school and shop brandsExample 9 of 10

Brand switcher: 4 themes

A list of seed colours and one state value. Tapping a swatch rebuilds the app with a new scheme. A white-label app can serve many clients from one code base.
class App extends StatefulWidget {
  const App({super.key});
  @override
  State<App> createState() => _AppState();
}
class _AppState extends State<App> {
  final brands = {'Ranchi Sweets': Colors.pink, 'Birsa Books': Colors.indigo, 'Hundru Tours': Colors.teal, 'Kanke Dairy': Colors.orange};
  late String current = brands.keys.first;
  @override
  Widget build(BuildContext context) => MaterialApp(
    theme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: brands[current]!)),
    home: Scaffold(
      appBar: AppBar(title: Text(current)),
      body: Padding(padding: const EdgeInsets.all(16), child: Column(children: [
        Wrap(spacing: 8, children: [for (final b in brands.keys) ChoiceChip(label: Text(b), selected: b == current, onSelected: (_) => setState(() => current = b))]),
        const SizedBox(height: 20),
        Card(child: ListTile(leading: const Icon(Icons.shopping_bag), title: const Text('Order 2041'), subtitle: const Text('Rs 1,450'), trailing: FilledButton(onPressed: () {}, child: const Text('Pay')))),
        const SizedBox(height: 12),
        const LinearProgressIndicator(value: 0.6),
      ])),
      floatingActionButton: FloatingActionButton(onPressed: () {}, child: const Icon(Icons.add)),
    ),
  );
}
void main() => runApp(const App());
Try it yourself: Add a fifth brand: Jharkhand Handloom with Colors.red.
Add a map entry.
HARDReal project: apps for elders and shop ownersExample 10 of 10

Accessible text size and contrast

A slider scales text with MediaQuery textScaler. Use scheme colour pairs (primary with onPrimary) so contrast stays readable. Layouts must not break at large text.
class Page extends StatefulWidget {
  const Page({super.key});
  @override
  State<Page> createState() => _PageState();
}
class _PageState extends State<Page> {
  double scale = 1;
  @override
  Widget build(BuildContext context) => MediaQuery(
    data: MediaQuery.of(context).copyWith(textScaler: TextScaler.linear(scale)),
    child: Scaffold(
      appBar: AppBar(title: const Text('Accessibility')),
      body: Padding(padding: const EdgeInsets.all(16), child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        Text('Text size: ${(scale * 100).round()}%'),
        Slider(value: scale, min: 0.8, max: 1.6, onChanged: (v) => setState(() => scale = v)),
        const Card(child: ListTile(title: Text('Electricity bill'), subtitle: Text('Due 25 Nov, Rs 1,820'), trailing: Icon(Icons.chevron_right))),
        const SizedBox(height: 12),
        FilledButton(onPressed: () {}, child: const Text('Pay now')),
      ])),
    ),
  );
}
void main() => runApp(MaterialApp(theme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue)), home: const Page()));
Try it yourself: Set the maximum to 2.0 and check for overflow.
max: 2.0 and scroll the card list.

Quick quiz

3 questions. Click an answer.
What does ColorScheme.fromSeed need?
A seedColorA fontAn iconA Navigator
Where should a dark mode switch live?
Inside a TextIn a StatefulWidget above MaterialAppIn pubspecIn Container
Best way to get the primary colour inside a screen?
Hard-code itTheme.of(context).colorScheme.primaryColors.redRandom
Score: 0 / 3

Recap: what you learned in Module 33

Seed

One colour creates the palette.

Theme.of

Never hard-code colours.

Dark mode

darkTheme + themeMode.

Component themes

Style buttons and cards once.

TextTheme

Shared type sizes.

Accessibility

Contrast pairs and scalable text.

Next: Responsive and Adaptive Design - One app, every screen size
MODULE 34 · PART 4

Responsive and Adaptive Design

One app, every screen size
You will learn
  • Read the screen with MediaQuery and LayoutBuilder
  • Choose layouts by width with breakpoints
  • Build flexible grids with Wrap, Flexible and GridView
  • Switch between bottom navigation and NavigationRail
  • Handle text scale, safe areas and orientation
You will build: a dashboard that becomes 1, 2 or 3 columns and switches between bottom bar and side rail
5 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
📱

Where is this used in real apps?

Your Ranchi shop app runs on a Rs 7,000 phone, a tablet at the counter and in a Chrome browser on the owner's laptop. One codebase must look right on all three.

LayoutBuilder

Gives the width available to a widget. Best way to pick a layout.

Breakpoints

Small under 600, medium 600 to 900, large above.

Adaptive

Different navigation per size: bottom bar, rail or drawer.

Dashboard
📈
Sales today
Rs 24,500
📦
Orders
38
👥
Customers
112

LayoutBuilder and breakpoints

LayoutBuilder tells you how much width you have. Use if (constraints.maxWidth < 600) to pick a layout. The preview helper below shows the same widget at 300, 600 and 900 pixels wide.

Honest note: a real phone is one size. This preview scales the layout of a wider screen down so you can see all three at once.
// Shows the child as if the screen were w x h pixels, scaled to fit.
Widget at(double w, double h, Widget c) => FittedBox(fit: BoxFit.contain, child: SizedBox(width: w, height: h, child: c));
class Resp extends StatelessWidget {
  const Resp({super.key});
  @override
  Widget build(BuildContext context) => LayoutBuilder(builder: (context, c) {
    final cols = c.maxWidth < 600 ? 1 : c.maxWidth < 900 ? 2 : 3;
    return Container(color: Colors.white, padding: const EdgeInsets.all(8), child: GridView.count(crossAxisCount: cols, childAspectRatio: 3, crossAxisSpacing: 8, mainAxisSpacing: 8, children: [
      for (var i = 1; i <= 6; i++) Container(color: Colors.indigo.shade100, alignment: Alignment.center, child: Text('Card $i  ($cols col)')),
    ]));
  });
}
void main() => runApp(MaterialApp(home: Scaffold(body: Column(children: [
  Expanded(child: at(300, 260, const Resp())), const Divider(),
  Expanded(child: at(700, 260, const Resp())), const Divider(),
  Expanded(child: at(1000, 260, const Resp())),
]))));

MediaQuery

MediaQuery.of(context).size is the whole screen. padding is the unsafe area (notch, status bar). orientation is portrait or landscape. For a part of the screen, prefer LayoutBuilder.

Tip: MediaQuery rebuilds the widget when the phone rotates. That is a feature, but also a cost on big screens.
class Page extends StatelessWidget {
  const Page({super.key});
  @override
  Widget build(BuildContext context) {
    final mq = MediaQuery.of(context);
    return Scaffold(
      appBar: AppBar(title: const Text('MediaQuery')),
      body: Padding(padding: const EdgeInsets.all(20), child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        Text('Width: ${mq.size.width.round()}'),
        Text('Height: ${mq.size.height.round()}'),
        Text('Orientation: ${mq.orientation.name}'),
        Text('Text scale: ${mq.textScaler.scale(1)}'),
        const SizedBox(height: 16),
        Container(width: mq.size.width * 0.5, height: 40, color: Colors.teal, alignment: Alignment.center, child: const Text('50% of width', style: TextStyle(color: Colors.white))),
      ])),
    );
  }
}
void main() => runApp(const MaterialApp(home: Page()));

Flexible grids: Wrap and GridView

Wrap puts as many children in a row as fit, then wraps to the next row. GridView.extent (maxCrossAxisExtent) picks the number of columns for you.

Rule: when you do not know the width, ask for a maximum tile size, not a fixed number of columns.
class Page extends StatelessWidget {
  const Page({super.key});
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Wrap and extent')),
    body: Padding(padding: const EdgeInsets.all(12), child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      const Text('Wrap'),
      Wrap(spacing: 8, runSpacing: 8, children: [for (final t in ['Dhuska', 'Litti', 'Thekua', 'Chilka', 'Rugra', 'Pittha', 'Handia']) Chip(label: Text(t))]),
      const SizedBox(height: 16),
      const Text('GridView.extent (tiles up to 110 wide)'),
      Expanded(child: GridView.extent(maxCrossAxisExtent: 110, mainAxisSpacing: 8, crossAxisSpacing: 8, children: [for (var i = 1; i <= 8; i++) Container(color: Colors.orange.shade200, alignment: Alignment.center, child: Text('$i'))])),
    ])),
  );
}
void main() => runApp(const MaterialApp(home: Page()));

Adaptive navigation

On a phone use a NavigationBar at the bottom. On wide screens use a NavigationRail on the left. The pages stay the same; only the frame changes.

Honest note: the two previews are scaled copies of the same Shell widget at 360 px and 900 px wide.
// Shows the child as if the screen were w x h pixels, scaled to fit.
Widget at(double w, double h, Widget c) => FittedBox(fit: BoxFit.contain, child: SizedBox(width: w, height: h, child: c));
class Shell extends StatefulWidget {
  const Shell({super.key});
  @override
  State<Shell> createState() => _ShellState();
}
class _ShellState extends State<Shell> {
  int i = 0;
  final pages = const ['Home', 'Orders', 'Profile'];
  @override
  Widget build(BuildContext context) => LayoutBuilder(builder: (context, c) {
    final wide = c.maxWidth >= 600;
    final body = Center(child: Text(pages[i], style: const TextStyle(fontSize: 28)));
    return Scaffold(
      body: wide ? Row(children: [
        NavigationRail(selectedIndex: i, onDestinationSelected: (v) => setState(() => i = v), labelType: NavigationRailLabelType.all, destinations: const [
          NavigationRailDestination(icon: Icon(Icons.home), label: Text('Home')),
          NavigationRailDestination(icon: Icon(Icons.receipt_long), label: Text('Orders')),
          NavigationRailDestination(icon: Icon(Icons.person), label: Text('Profile')),
        ]),
        Expanded(child: body),
      ]) : body,
      bottomNavigationBar: wide ? null : NavigationBar(selectedIndex: i, onDestinationSelected: (v) => setState(() => i = v), destinations: const [
        NavigationDestination(icon: Icon(Icons.home), label: 'Home'),
        NavigationDestination(icon: Icon(Icons.receipt_long), label: 'Orders'),
        NavigationDestination(icon: Icon(Icons.person), label: 'Profile'),
      ]),
    );
  });
}
void main() => runApp(MaterialApp(home: Scaffold(body: Column(children: [
  Expanded(child: at(360, 400, const Shell())), const Divider(),
  Expanded(child: at(640, 360, const Shell())),
]))));

Animated explainer: Breakpoints

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

Animated explainer: LayoutBuilder flow

Press Next to walk through it step by step, or Auto play.
EASYReal project: debugging layoutsExample 1 of 10

Screen size readout

MediaQuery.sizeOf(context) is the quickest way to learn the screen width and height.
void main() {
  runApp(MaterialApp(home: Builder(builder: (context) {
    final s = MediaQuery.sizeOf(context);
    return Scaffold(body: Center(child: Text('${s.width.round()} x ${s.height.round()}', style: const TextStyle(fontSize: 36))));
  })));
}
Try it yourself: Add a Text showing the orientation.
MediaQuery.orientationOf(context).name.
EASYReal project: hero banners and cardsExample 2 of 10

Half-width box

Multiply the width by a fraction. Better: FractionallySizedBox(widthFactor: 0.5) does the same without MediaQuery.
void main() {
  runApp(const MaterialApp(home: Scaffold(body: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
    FractionallySizedBox(widthFactor: 0.5, child: ColoredBox(color: Colors.teal, child: SizedBox(height: 50, child: Center(child: Text('50%', style: TextStyle(color: Colors.white)))))),
    SizedBox(height: 12),
    FractionallySizedBox(widthFactor: 0.8, child: ColoredBox(color: Colors.orange, child: SizedBox(height: 50, child: Center(child: Text('80%'))))),
  ]))));
}
Try it yourself: Make the second box 100% wide.
widthFactor: 1.
EASYReal project: tags, filters, size optionsExample 3 of 10

Wrap chips

Wrap flows items onto new lines, so it works on any width without a breakpoint.
void main() {
  runApp(MaterialApp(home: Scaffold(
    appBar: AppBar(title: const Text('Filters')),
    body: Padding(padding: const EdgeInsets.all(16), child: Wrap(spacing: 8, runSpacing: 8, children: [
      for (final t in ['Under Rs 500', 'Free delivery', 'Open now', 'Veg only', 'Near Kanke', 'Rating 4+', 'Offers', 'Home made']) FilterChip(label: Text(t), selected: t.length % 2 == 0, onSelected: (_) {}),
    ])),
  )));
}
Try it yourself: Add three more filters.
Add strings to the list.
EASYReal project: product galleriesExample 4 of 10

Max tile width grid

GridView.extent chooses the number of columns from a maximum tile width.
void main() {
  runApp(MaterialApp(home: Scaffold(
    appBar: AppBar(title: const Text('Products')),
    body: GridView.extent(maxCrossAxisExtent: 120, padding: const EdgeInsets.all(8), mainAxisSpacing: 8, crossAxisSpacing: 8, children: [
      for (var i = 1; i <= 10; i++) Card(child: Center(child: Text('Item $i'))),
    ]),
  )));
}
Try it yourself: Use maxCrossAxisExtent: 180 and count the columns.
Change the number.
EASYReal project: avoiding notches and bottom gesture barsExample 5 of 10

Safe area

SafeArea adds padding so content avoids the status bar and rounded corners.
void main() {
  runApp(MaterialApp(home: Scaffold(
    backgroundColor: Colors.indigo,
    body: SafeArea(child: Container(color: Colors.white, alignment: Alignment.center, child: const Text('Inside the safe area'))),
  )));
}
Try it yourself: Remove SafeArea and compare.
Replace it with its child.
MEDIUMReal project: dashboards and product pagesExample 6 of 10

1, 2 or 3 columns

LayoutBuilder picks the column count from the width. The same code shows 1, 2 or 3 columns.
// Shows the child as if the screen were w x h pixels, scaled to fit.
Widget at(double w, double h, Widget c) => FittedBox(fit: BoxFit.contain, child: SizedBox(width: w, height: h, child: c));
class Grid extends StatelessWidget {
  const Grid({super.key});
  @override
  Widget build(BuildContext context) => LayoutBuilder(builder: (context, c) {
    final n = c.maxWidth >= 900 ? 3 : c.maxWidth >= 600 ? 2 : 1;
    return GridView.count(crossAxisCount: n, childAspectRatio: 3.2, padding: const EdgeInsets.all(8), crossAxisSpacing: 8, mainAxisSpacing: 8, children: [
      for (final m in [['Sales', 'Rs 24,500'], ['Orders', '38'], ['Customers', '112'], ['Returns', '2'], ['Rating', '4.6'], ['Visits', '1,204']]) Card(child: Center(child: Text('${m[0]}: ${m[1]}', style: const TextStyle(fontSize: 18)))),
    ]);
  });
}
void main() => runApp(MaterialApp(home: Scaffold(body: Column(children: [
  Expanded(child: at(360, 300, const Grid())), Expanded(child: at(700, 300, const Grid())), Expanded(child: at(1000, 300, const Grid())),
]))));
Try it yourself: Add a fourth breakpoint at 1200 with 4 columns.
Another comparison before the final else.
MEDIUMReal project: contact sections and product detailsExample 7 of 10

Row on wide, Column on narrow

Same widgets, different parent. On wide screens an image sits beside the text; on narrow ones it sits above.
// Shows the child as if the screen were w x h pixels, scaled to fit.
Widget at(double w, double h, Widget c) => FittedBox(fit: BoxFit.contain, child: SizedBox(width: w, height: h, child: c));
class Detail extends StatelessWidget {
  const Detail({super.key});
  @override
  Widget build(BuildContext context) => LayoutBuilder(builder: (context, c) {
    final img = Container(width: 160, height: 120, color: Colors.teal.shade200, child: const Icon(Icons.image, size: 48, color: Colors.white));
    const info = Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Text('Ranchi Handloom Saree', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), Text('Rs 1,850 - free delivery in Jharkhand')]));
    return Padding(padding: const EdgeInsets.all(12), child: c.maxWidth >= 600
      ? Row(children: [img, const SizedBox(width: 16), info])
      : Column(children: [img, const SizedBox(height: 12), const Text('Ranchi Handloom Saree', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), const Text('Rs 1,850 - free delivery in Jharkhand')]));
  });
}
void main() => runApp(MaterialApp(home: Scaffold(body: Column(children: [
  Expanded(child: at(340, 240, const Detail())), const Divider(), Expanded(child: at(800, 200, const Detail())),
]))));
Try it yourself: Add a Buy button after the price in both layouts.
Put the same FilledButton in each branch.
MEDIUMReal project: web pages and long formsExample 8 of 10

Max width reading column

On a wide screen, text lines become too long to read. ConstrainedBox(maxWidth: 600) inside a Center keeps a readable column.
// Shows the child as if the screen were w x h pixels, scaled to fit.
Widget at(double w, double h, Widget c) => FittedBox(fit: BoxFit.contain, child: SizedBox(width: w, height: h, child: c));
class Article extends StatelessWidget {
  const Article({super.key});
  @override
  Widget build(BuildContext context) => Scaffold(body: Center(child: ConstrainedBox(
    constraints: const BoxConstraints(maxWidth: 500),
    child: const Padding(padding: EdgeInsets.all(16), child: Text('Jharkhand has more than 30 percent of its area under forest. Hundru Falls drops 98 metres and is one of the most visited places near Ranchi. Keeping lines short makes long text easier to read on big screens.', style: TextStyle(fontSize: 16, height: 1.5))),
  )));
}
void main() => runApp(MaterialApp(home: Scaffold(body: Column(children: [
  Expanded(child: at(400, 260, const Article())), const Divider(), Expanded(child: at(1000, 260, const Article())),
]))));
Try it yourself: Change maxWidth to 320.
BoxConstraints maxWidth.
HARDReal project: admin panels and shop dashboardsExample 9 of 10

Adaptive dashboard with rail

Combines everything: the navigation switches between bottom bar and rail, the card grid changes its columns, and one widget serves phone and laptop.
// Shows the child as if the screen were w x h pixels, scaled to fit.
Widget at(double w, double h, Widget c) => FittedBox(fit: BoxFit.contain, child: SizedBox(width: w, height: h, child: c));
class Dash extends StatefulWidget {
  const Dash({super.key});
  @override
  State<Dash> createState() => _DashState();
}
class _DashState extends State<Dash> {
  int i = 0;
  @override
  Widget build(BuildContext context) => LayoutBuilder(builder: (context, c) {
    final wide = c.maxWidth >= 700;
    final stats = [['Sales', 'Rs 24,500', Icons.currency_rupee], ['Orders', '38', Icons.receipt_long], ['Customers', '112', Icons.people], ['Returns', '2', Icons.undo]];
    final grid = GridView.count(crossAxisCount: wide ? 4 : 2, childAspectRatio: wide ? 1.6 : 1.5, padding: const EdgeInsets.all(8), mainAxisSpacing: 8, crossAxisSpacing: 8, children: [
      for (final s in stats) Card(child: Padding(padding: const EdgeInsets.all(12), child: Column(crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [Icon(s[2] as IconData), Text(s[1] as String, style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold)), Text(s[0] as String)]))),
    ]);
    return Scaffold(
      appBar: AppBar(title: const Text('Shop dashboard')),
      body: Row(children: [
        if (wide) NavigationRail(selectedIndex: i, onDestinationSelected: (v) => setState(() => i = v), destinations: const [
          NavigationRailDestination(icon: Icon(Icons.dashboard), label: Text('Home')),
          NavigationRailDestination(icon: Icon(Icons.inventory_2), label: Text('Stock')),
          NavigationRailDestination(icon: Icon(Icons.settings), label: Text('Settings')),
        ]),
        Expanded(child: grid),
      ]),
      bottomNavigationBar: wide ? null : NavigationBar(selectedIndex: i, onDestinationSelected: (v) => setState(() => i = v), destinations: const [
        NavigationDestination(icon: Icon(Icons.dashboard), label: 'Home'),
        NavigationDestination(icon: Icon(Icons.inventory_2), label: 'Stock'),
        NavigationDestination(icon: Icon(Icons.settings), label: 'Settings'),
      ]),
    );
  });
}
void main() => runApp(MaterialApp(home: Scaffold(body: Column(children: [
  Expanded(child: at(360, 480, const Dash())), const Divider(), Expanded(child: at(760, 380, const Dash())),
]))));
Try it yourself: Show a detail panel on the right when the width is 1100 or more.
Add a third child to the Row guarded by an if.
HARDReal project: email, chat and order appsExample 10 of 10

Master-detail (list and detail)

On wide screens the list and the selected item show side by side. On narrow screens tapping an item opens the detail full screen. This is the classic adaptive pattern.
// Shows the child as if the screen were w x h pixels, scaled to fit.
Widget at(double w, double h, Widget c) => FittedBox(fit: BoxFit.contain, child: SizedBox(width: w, height: h, child: c));
class Orders extends StatefulWidget {
  const Orders({super.key});
  @override
  State<Orders> createState() => _OrdersState();
}
class _OrdersState extends State<Orders> {
  final names = ['Order 1041 - Ravi', 'Order 1042 - Sunita', 'Order 1043 - Amit'];
  int sel = 0;
  Widget detail(int i) => Center(child: Text('Details of\n${names[i]}', textAlign: TextAlign.center, style: const TextStyle(fontSize: 22)));
  @override
  Widget build(BuildContext context) => LayoutBuilder(builder: (context, c) {
    final list = ListView(children: [for (var i = 0; i < names.length; i++) ListTile(selected: c.maxWidth >= 600 && i == sel, title: Text(names[i]), onTap: () {
      if (c.maxWidth >= 600) { setState(() => sel = i); } else { Navigator.push(context, MaterialPageRoute(builder: (_) => Scaffold(appBar: AppBar(title: Text(names[i])), body: detail(i)))); }
    })]);
    return Scaffold(appBar: AppBar(title: const Text('Orders')), body: c.maxWidth >= 600 ? Row(children: [SizedBox(width: 260, child: list), const VerticalDivider(width: 1), Expanded(child: detail(sel))]) : list);
  });
}
void main() => runApp(MaterialApp(home: Scaffold(body: Column(children: [
  Expanded(child: at(360, 280, const Orders())), const Divider(), Expanded(child: at(640, 260, const Orders())),
]))));
Try it yourself: Add a fourth order and a Mark shipped button in the detail.
Add to names; a FilledButton under the Text.

Quick quiz

3 questions. Click an answer.
Which widget tells you the width available to one widget?
LayoutBuilderScaffoldIconPadding
On a wide screen, which navigation widget is usual?
NavigationRailSnackbarTooltipAppBar only
GridView.extent chooses columns from:
A fixed countA maximum tile widthThe themeRandom
Score: 0 / 3

Recap: what you learned in Module 34

LayoutBuilder

Pick layout from width.

Breakpoints

600 and 900 are common.

MediaQuery

Screen size, padding, text scale.

Wrap and extent

Flow without breakpoints.

Adaptive nav

Bottom bar to rail.

Master-detail

Side by side on wide screens.

Next: Custom Painting, Clipping and Effects - Draw anything the widgets do not have
MODULE 35 · PART 4

Custom Painting, Clipping and Effects

Draw anything the widgets do not have
You will learn
  • Draw with CustomPaint, Canvas, Paint and Path
  • Draw arcs for rings and gauges
  • Clip widgets into circles, rounded shapes and waves
  • Apply gradient and colour effects with ShaderMask and ColorFiltered
  • Build your own charts without any package
You will build: a progress ring, a bar chart, a line chart, a wavy header and an analog clock
5 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
🎨

Where is this used in real apps?

Fitness rings, sales charts, wavy login headers, circular avatars, a speedometer. When no ready-made widget exists you can draw it yourself, and it is lighter than a chart package.

CustomPaint

A widget with a painter. You get a Canvas and a Size, and you draw on it.

Clip

ClipOval, ClipRRect and ClipPath cut a child to a shape.

Effects

ShaderMask, ColorFiltered and BackdropFilter change how a child looks.

Fit Ranchi
⏱
Steps today
6,420 of 8,000
🔥
Calories
310
💧
Water
5 of 8 glasses

CustomPaint and CustomPainter

Make a class that extends CustomPainter and write paint(Canvas canvas, Size size). Put it in a CustomPaint with a size. The canvas origin (0,0) is the top-left corner.

Tip: shouldRepaint returns true only when your data changed. Returning false for static drawings saves battery.
class Shapes extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final fill = Paint()..color = Colors.indigo;
    final line = Paint()..color = Colors.orange..strokeWidth = 6..style = PaintingStyle.stroke;
    canvas.drawRect(const Rect.fromLTWH(20, 20, 120, 80), fill);
    canvas.drawCircle(const Offset(220, 60), 40, Paint()..color = Colors.teal);
    canvas.drawLine(const Offset(20, 140), const Offset(260, 140), line);
  }
  @override
  bool shouldRepaint(covariant CustomPainter old) => false;
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Center(child: CustomPaint(size: Size(300, 180), painter: Shapes())))));

Paint and Path

Paint says how to draw: colour, style (fill or stroke), strokeWidth, strokeCap. Path is a route: moveTo, lineTo, curves, close. Then canvas.drawPath(path, paint).

Order matters: later drawing covers earlier drawing, like layers of paper.
class Tri extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final p = Path()
      ..moveTo(size.width / 2, 20)
      ..lineTo(size.width - 30, size.height - 30)
      ..lineTo(30, size.height - 30)
      ..close();
    canvas.drawPath(p, Paint()..color = Colors.orange.shade200);
    canvas.drawPath(p, Paint()..color = Colors.deepOrange..style = PaintingStyle.stroke..strokeWidth = 5..strokeJoin = StrokeJoin.round);
  }
  @override
  bool shouldRepaint(covariant CustomPainter old) => false;
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Center(child: CustomPaint(size: Size(280, 240), painter: Tri())))));

Clipping widgets

ClipOval makes a circle, ClipRRect rounds corners, ClipPath uses any Path. Clipping cuts what is drawn but does not change the size the widget takes.

Cost: clipping is a little expensive. Use it on small widgets, not on an entire long list.
void main() {
  runApp(MaterialApp(home: Scaffold(body: Center(child: Row(mainAxisSize: MainAxisSize.min, children: [
    ClipOval(child: Container(width: 90, height: 90, color: Colors.teal, child: const Icon(Icons.person, size: 60, color: Colors.white))),
    const SizedBox(width: 16),
    ClipRRect(borderRadius: BorderRadius.circular(24), child: Container(width: 90, height: 90, color: Colors.orange, child: const Icon(Icons.store, size: 60, color: Colors.white))),
  ])))));
}

Effects: ShaderMask and ColorFiltered

ShaderMask paints a gradient through a child, great for gradient text. ColorFiltered changes every colour in the child, for example to grey for a disabled look. BackdropFilter blurs what is behind a widget.

Honest note: the slide engine draws these effects with CSS. Real Flutter uses the GPU, and BlendModes other than the common ones may differ.
void main() {
  runApp(MaterialApp(home: Scaffold(body: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
    ShaderMask(
      shaderCallback: (r) => const LinearGradient(colors: [Colors.deepPurple, Colors.pink, Colors.orange]).createShader(r),
      child: const Text('Ranchi Sale', style: TextStyle(fontSize: 44, fontWeight: FontWeight.bold, color: Colors.white)),
    ),
    const SizedBox(height: 20),
    ColorFiltered(colorFilter: const ColorFilter.mode(Colors.grey, BlendMode.saturation), child: Container(width: 120, height: 80, color: Colors.red, child: const Center(child: Text('Sold out', style: TextStyle(color: Colors.white))))),
  ])))));
}

Animated explainer: How CustomPaint works

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

Animated explainer: From data to chart

Press Next to walk through it step by step, or Auto play.
EASYReal project: icons, badges and logosExample 1 of 10

Draw basic shapes

A rectangle, a circle, a line and an oval on one canvas. Everything is positioned from the top-left corner.
class P extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    canvas.drawRect(const Rect.fromLTWH(10, 10, 100, 60), Paint()..color = Colors.blue);
    canvas.drawCircle(const Offset(180, 40), 30, Paint()..color = Colors.green);
    canvas.drawOval(const Rect.fromLTWH(10, 100, 120, 60), Paint()..color = Colors.orange);
    canvas.drawLine(const Offset(150, 110), const Offset(260, 160), Paint()..color = Colors.red..strokeWidth = 5);
  }
  @override
  bool shouldRepaint(covariant CustomPainter old) => false;
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Center(child: CustomPaint(size: Size(280, 180), painter: P())))));
Try it yourself: Add a purple circle at (230, 140) with radius 15.
drawCircle with another Paint.
EASYReal project: emoji and rating facesExample 2 of 10

Smiley face

A circle, two small circles and an arc for the smile. drawArc takes a rectangle, a start angle, a sweep angle and whether to connect to the centre.
import 'dart:math';
class Face extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final c = Offset(size.width / 2, size.height / 2);
    canvas.drawCircle(c, 90, Paint()..color = Colors.amber);
    canvas.drawCircle(c + const Offset(-30, -25), 10, Paint()..color = Colors.black);
    canvas.drawCircle(c + const Offset(30, -25), 10, Paint()..color = Colors.black);
    canvas.drawArc(Rect.fromCenter(center: c + const Offset(0, 15), width: 90, height: 60), 0, pi, false, Paint()..color = Colors.black..style = PaintingStyle.stroke..strokeWidth = 6..strokeCap = StrokeCap.round);
  }
  @override
  bool shouldRepaint(covariant CustomPainter old) => false;
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Center(child: CustomPaint(size: Size(240, 240), painter: Face())))));
Try it yourself: Make a sad face: start the arc at pi and sweep pi, and move it up.
Change start angle and the Offset y.
EASYReal project: fitness rings and exam scoreExample 3 of 10

Progress ring

Two arcs: a grey full circle behind, and a coloured arc whose sweep is progress * 2 * pi. Start at -pi/2 so it begins at the top.
import 'dart:math';
class Ring extends CustomPainter {
  final double value;
  Ring(this.value);
  @override
  void paint(Canvas canvas, Size size) {
    final r = Rect.fromCircle(center: Offset(size.width / 2, size.height / 2), radius: 80);
    canvas.drawArc(r, 0, 2 * pi, false, Paint()..color = Colors.grey.shade300..style = PaintingStyle.stroke..strokeWidth = 16);
    canvas.drawArc(r, -pi / 2, 2 * pi * value, false, Paint()..color = Colors.teal..style = PaintingStyle.stroke..strokeWidth = 16..strokeCap = StrokeCap.round);
  }
  @override
  bool shouldRepaint(covariant Ring old) => old.value != value;
}
void main() {
  runApp(const MaterialApp(home: Scaffold(body: Center(child: Stack(alignment: Alignment.center, children: [
    CustomPaint(size: Size(220, 220), painter: Ring(0.8)),
    Text('6,420\nsteps', textAlign: TextAlign.center, style: TextStyle(fontSize: 24)),
  ])))));
}
Try it yourself: Change the value to 0.35 and the colour to orange.
Edit the number and the Paint colour.
EASYReal project: profile picturesExample 4 of 10

Circular avatar and rounded image

ClipOval turns any widget into a circle. ClipRRect rounds corners. Both keep the original size of the box.
void main() {
  runApp(MaterialApp(home: Scaffold(
    appBar: AppBar(title: const Text('Profile')),
    body: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
      ClipOval(child: Container(width: 110, height: 110, color: Colors.indigo.shade200, child: const Icon(Icons.person, size: 80, color: Colors.white))),
      const SizedBox(height: 12),
      const Text('Anita Kumari', style: TextStyle(fontSize: 22)),
      const SizedBox(height: 20),
      ClipRRect(borderRadius: BorderRadius.circular(16), child: Container(width: 260, height: 90, color: Colors.orange.shade200, child: const Center(child: Text('Ranchi, Jharkhand')))),
    ])),
  )));
}
Try it yourself: Make the second box more rounded.
BorderRadius.circular(40).
EASYReal project: brand titles and offersExample 5 of 10

Gradient text

ShaderMask with a LinearGradient paints colour through the text shape. The text must be white so the gradient shows fully.
void main() {
  runApp(MaterialApp(home: Scaffold(body: Center(child: ShaderMask(
    shaderCallback: (bounds) => const LinearGradient(colors: [Colors.blue, Colors.purple, Colors.red]).createShader(bounds),
    child: const Text('Diwali Offer', style: TextStyle(fontSize: 48, fontWeight: FontWeight.w900, color: Colors.white)),
  )))));
}
Try it yourself: Use orange and yellow colours.
Change the colors list.
MEDIUMReal project: login and onboarding screensExample 6 of 10

Wavy header

ClipPath with a CustomClipper cuts the bottom of a coloured box into a wave using quadraticBezierTo.
class Wave extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    final p = Path()..lineTo(0, size.height - 40)
      ..quadraticBezierTo(size.width / 4, size.height, size.width / 2, size.height - 30)
      ..quadraticBezierTo(size.width * 3 / 4, size.height - 60, size.width, size.height - 20)
      ..lineTo(size.width, 0)
      ..close();
    return p;
  }
  @override
  bool shouldReclip(covariant CustomClipper<Path> old) => false;
}
void main() {
  runApp(MaterialApp(home: Scaffold(body: Column(children: [
    ClipPath(clipper: Wave(), child: Container(height: 220, width: double.infinity, color: Colors.indigo, alignment: Alignment.center, child: const Text('Welcome back', style: TextStyle(color: Colors.white, fontSize: 28)))),
    const Padding(padding: EdgeInsets.all(24), child: TextField(decoration: InputDecoration(labelText: 'Phone number'))),
  ]))));
}
Try it yourself: Change the wave heights to make it steeper.
Edit the y values in quadraticBezierTo.
MEDIUMReal project: sales dashboardsExample 7 of 10

Bar chart from scratch

Scale each value by the maximum, then draw one rounded rectangle per value. Month names are normal Text widgets under the canvas.
class Bars extends CustomPainter {
  final List<double> data;
  Bars(this.data);
  @override
  void paint(Canvas canvas, Size size) {
    final maxV = data.reduce((a, b) => a > b ? a : b);
    final w = size.width / data.length;
    for (var i = 0; i < data.length; i++) {
      final h = data[i] / maxV * (size.height - 10);
      final r = RRect.fromRectAndRadius(Rect.fromLTWH(i * w + 8, size.height - h, w - 16, h), const Radius.circular(6));
      canvas.drawRRect(r, Paint()..color = i == data.length - 1 ? Colors.deepOrange : Colors.indigo.shade300);
    }
  }
  @override
  bool shouldRepaint(covariant Bars old) => old.data != data;
}
void main() {
  const months = ['Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov'];
  runApp(MaterialApp(home: Scaffold(
    appBar: AppBar(title: const Text('Sales (lakh Rs)')),
    body: Padding(padding: const EdgeInsets.all(20), child: Column(children: [
      const SizedBox(height: 20),
      CustomPaint(size: const Size(300, 200), painter: Bars([2.4, 3.1, 2.8, 4.0, 4.6, 5.2])),
      Row(mainAxisAlignment: MainAxisAlignment.spaceAround, children: [for (final m in months) Text(m, style: const TextStyle(fontSize: 12))]),
    ])),
  )));
}
Try it yourself: Add a seventh month, Dec, with 5.9.
Add to both lists.
MEDIUMReal project: stock, temperature and traffic graphsExample 8 of 10

Line chart with filled area

Build one Path through the points. Draw it once as a line, then close it down to the baseline and fill with a gradient.
class Line extends CustomPainter {
  final List<double> d;
  Line(this.d);
  @override
  void paint(Canvas canvas, Size size) {
    final maxV = d.reduce((a, b) => a > b ? a : b), minV = d.reduce((a, b) => a < b ? a : b);
    final dx = size.width / (d.length - 1);
    Offset pt(int i) => Offset(i * dx, size.height - (d[i] - minV) / (maxV - minV) * (size.height - 20) - 10);
    final line = Path()..moveTo(pt(0).dx, pt(0).dy);
    for (var i = 1; i < d.length; i++) { line.lineTo(pt(i).dx, pt(i).dy); }
    final area = Path.from(line)..lineTo(size.width, size.height)..lineTo(0, size.height)..close();
    canvas.drawPath(area, Paint()..color = Colors.teal.withOpacity(0.2));
    canvas.drawPath(line, Paint()..color = Colors.teal..style = PaintingStyle.stroke..strokeWidth = 4..strokeJoin = StrokeJoin.round);
    for (var i = 0; i < d.length; i++) { canvas.drawCircle(pt(i), 5, Paint()..color = Colors.teal.shade800); }
  }
  @override
  bool shouldRepaint(covariant Line old) => old.d != d;
}
void main() {
  runApp(MaterialApp(home: Scaffold(
    appBar: AppBar(title: const Text('Ranchi temperature (C)')),
    body: Center(child: CustomPaint(size: const Size(310, 220), painter: Line([18, 21, 26, 31, 29, 24, 19]))),
  )));
}
Try it yourself: Make the area fully transparent and the line orange.
Paint colours.
HARDReal project: clocks, timers and gaugesExample 9 of 10

Animated analog clock

A Timer calls setState every second. The painter computes each hand angle from the time with sin and cos and draws tick marks in a loop. This is how speedometers and dials are built.
import 'dart:math';
import 'dart:async';

class ClockPainter extends CustomPainter {
  final DateTime t;
  ClockPainter(this.t);
  @override
  void paint(Canvas canvas, Size size) {
    final c = Offset(size.width / 2, size.height / 2);
    final r = size.width / 2 - 6;
    canvas.drawCircle(c, r, Paint()..color = Colors.white);
    canvas.drawCircle(c, r, Paint()..color = Colors.indigo..style = PaintingStyle.stroke..strokeWidth = 6);
    for (var i = 0; i < 12; i++) {
      final a = i * pi / 6;
      canvas.drawLine(c + Offset(sin(a), -cos(a)) * (r - 14), c + Offset(sin(a), -cos(a)) * (r - 4), Paint()..color = Colors.black..strokeWidth = 3);
    }
    void hand(double angle, double len, double w, Color col) => canvas.drawLine(c, c + Offset(sin(angle), -cos(angle)) * len, Paint()..color = col..strokeWidth = w..strokeCap = StrokeCap.round);
    hand((t.hour % 12 + t.minute / 60) * pi / 6, r * 0.5, 6, Colors.black);
    hand((t.minute + t.second / 60) * pi / 30, r * 0.75, 4, Colors.black);
    hand(t.second * pi / 30, r * 0.85, 2, Colors.red);
    canvas.drawCircle(c, 6, Paint()..color = Colors.red);
  }
  @override
  bool shouldRepaint(covariant ClockPainter old) => old.t != t;
}
class Clock extends StatefulWidget {
  const Clock({super.key});
  @override
  State<Clock> createState() => _ClockState();
}
class _ClockState extends State<Clock> {
  DateTime now = DateTime.now();
  Timer? timer;
  @override
  void initState() {
    super.initState();
    timer = Timer.periodic(const Duration(seconds: 1), (_) => setState(() => now = DateTime.now()));
  }
  @override
  void dispose() { timer?.cancel(); super.dispose(); }
  @override
  Widget build(BuildContext context) => Scaffold(body: Center(child: CustomPaint(size: const Size(260, 260), painter: ClockPainter(now))));
}
void main() => runApp(const MaterialApp(home: Clock()));
Try it yourself: Add a small digital time Text below the clock.
Wrap in Column; use now.hour and now.minute.
HARDReal project: expense and category breakdownsExample 10 of 10

Interactive donut chart

Each slice is an arc with its own sweep (value / total * 2 pi). Tap a legend item to highlight that slice by drawing it thicker. State change repaints the canvas.
import 'dart:math';
class Donut extends CustomPainter {
  final List<double> v;
  final List<Color> colors;
  final int sel;
  Donut(this.v, this.colors, this.sel);
  @override
  void paint(Canvas canvas, Size size) {
    final total = v.fold(0.0, (a, b) => a + b);
    final rect = Rect.fromCircle(center: Offset(size.width / 2, size.height / 2), radius: 80);
    var start = -pi / 2;
    for (var i = 0; i < v.length; i++) {
      final sweep = v[i] / total * 2 * pi;
      canvas.drawArc(rect, start, sweep - 0.03, false, Paint()..color = colors[i]..style = PaintingStyle.stroke..strokeWidth = i == sel ? 36 : 24);
      start += sweep;
    }
  }
  @override
  bool shouldRepaint(covariant Donut old) => old.sel != sel;
}
class Page extends StatefulWidget {
  const Page({super.key});
  @override
  State<Page> createState() => _PageState();
}
class _PageState extends State<Page> {
  final names = ['Rent', 'Food', 'Travel', 'Fees'];
  final vals = [12000.0, 8000.0, 3000.0, 5000.0];
  final cols = [Colors.indigo, Colors.orange, Colors.teal, Colors.pink];
  int sel = 0;
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Monthly expenses')),
    body: Column(children: [
      CustomPaint(size: const Size(260, 220), painter: Donut(vals, cols, sel)),
      Text('${names[sel]}: Rs ${vals[sel].round()}', style: const TextStyle(fontSize: 20)),
      Wrap(spacing: 8, children: [for (var i = 0; i < names.length; i++) ChoiceChip(label: Text(names[i]), selected: sel == i, onSelected: (_) => setState(() => sel = i))]),
    ]),
  );
}
void main() => runApp(const MaterialApp(home: Page()));
Try it yourself: Show the percentage of the selected slice.
vals[sel] / total * 100.

Quick quiz

3 questions. Click an answer.
Where is the canvas origin (0, 0)?
Top-leftCentreBottom-leftTop-right
Which Paint style draws only an outline?
PaintingStyle.strokePaintingStyle.fillStyle.linePaint.border
ClipPath needs:
A CustomClipper returning a PathA ControllerA NavigatorA Key
Score: 0 / 3

Recap: what you learned in Module 35

CustomPaint

paint(canvas, size) draws.

Paint and Path

How and where.

Arcs

Rings and donuts.

Clip widgets

Oval, RRect, Path.

Effects

ShaderMask and ColorFiltered.

Charts

Scale values, loop, draw.

Next: UI Design Practice and Capstone - Turn skills into polished screens and a portfolio
MODULE 36 · PART 4

UI Design Practice and Capstone

Turn skills into polished screens and a portfolio
You will learn
  • Use an 8-point spacing system and a clear type hierarchy
  • Design empty, error and success states
  • Redesign screens for real local businesses
  • Apply a 12-point design checklist
  • Build a portfolio and plan your next steps
You will build: six redesigned screens for Ranchi businesses and your design portfolio
6 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
🎓

Where is this used in real apps?

Two apps can have the same features, but the one with better spacing, clear text and friendly empty screens feels professional. Clients pay for that feeling.

Spacing and type

A small system beats guessing every number.

All states

Loading, empty and error screens are part of the design.

Portfolio

Before and after screenshots prove your skill.

Dhaba Menu
🍳
Litti Chokha
Rs 120
🍲
Dal Pittha
Rs 90
🍰
Thekua
Rs 40

The 8-point spacing system

Choose spacing only from 4, 8, 16, 24, 32, 48. Put them in constants so every screen shares them. Related items get small gaps; separate groups get big gaps.

Tip: when two gaps look almost the same but are 14 and 16, make them both 16. Consistency looks like quality.
class Gap {
  static const s = 8.0, m = 16.0, l = 24.0;
}
class Page extends StatelessWidget {
  const Page({super.key});
  Widget card(String t, String s) => Card(child: Padding(padding: const EdgeInsets.all(Gap.m), child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
    Text(t, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
    const SizedBox(height: Gap.s),
    Text(s),
  ])));
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Spacing')),
    body: ListView(padding: const EdgeInsets.all(Gap.m), children: [
      card('Fee reminder', 'Your November fee of Rs 1,500 is due on 25 Nov.'),
      const SizedBox(height: Gap.m),
      card('New batch', 'Flutter batch starts Monday at 7 AM.'),
      const SizedBox(height: Gap.l),
      card('Holiday', 'Centre closed on 15 Nov for Jharkhand Foundation Day.'),
    ]),
  );
}
void main() => runApp(const MaterialApp(home: Page()));

Type hierarchy

Readers scan. Make one thing clearly biggest (title), body text comfortable (16), and extra info small and grey (caption). Use weight and colour, not only size.

Squint test: blur your eyes. If you can still tell what is most important, your hierarchy works.
void main() {
  runApp(MaterialApp(home: Scaffold(body: Padding(padding: const EdgeInsets.all(24), child: Column(mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [
    const Text('NEW ARRIVAL', style: TextStyle(fontSize: 12, letterSpacing: 1.5, color: Colors.deepOrange, fontWeight: FontWeight.bold)),
    const SizedBox(height: 4),
    const Text('Tussar Silk Saree', style: TextStyle(fontSize: 28, fontWeight: FontWeight.bold)),
    const SizedBox(height: 8),
    const Text('Hand woven in Jharkhand with natural dyes. Soft, light and perfect for weddings and festivals.', style: TextStyle(fontSize: 16, height: 1.5)),
    const SizedBox(height: 12),
    const Text('Rs 3,450', style: TextStyle(fontSize: 24, fontWeight: FontWeight.w700, color: Colors.teal)),
    const Text('Free delivery in Ranchi', style: TextStyle(fontSize: 12, color: Colors.grey)),
  ])))));
}

Empty, error and loading states

Every list has three more screens: loading, empty (no data yet) and error (something failed). Each should say what happened and what to do next, in friendly words.

Rule: an empty screen is a chance to guide the user, not just show a blank page.
class Page extends StatefulWidget {
  const Page({super.key});
  @override
  State<Page> createState() => _PageState();
}
class _PageState extends State<Page> {
  int state = 0;
  @override
  Widget build(BuildContext context) {
    final views = [
      const Center(child: CircularProgressIndicator()),
      Column(mainAxisAlignment: MainAxisAlignment.center, children: const [Icon(Icons.receipt_long, size: 72, color: Colors.grey), SizedBox(height: 12), Text('No orders yet', style: TextStyle(fontSize: 20)), Text('Your orders will show up here.', style: TextStyle(color: Colors.grey))]),
      Column(mainAxisAlignment: MainAxisAlignment.center, children: [const Icon(Icons.wifi_off, size: 72, color: Colors.red), const SizedBox(height: 12), const Text('No internet', style: TextStyle(fontSize: 20)), const SizedBox(height: 8), FilledButton(onPressed: () {}, child: const Text('Try again'))]),
    ];
    return Scaffold(
      appBar: AppBar(title: const Text('Orders')),
      body: Center(child: views[state]),
      bottomNavigationBar: SegmentedButton<int>(segments: const [ButtonSegment(value: 0, label: Text('Loading')), ButtonSegment(value: 1, label: Text('Empty')), ButtonSegment(value: 2, label: Text('Offline'))], selected: {state}, onSelectionChanged: (s) => setState(() => state = s.first)),
    );
  }
}
void main() => runApp(const MaterialApp(home: Page()));

Status colour plus icon plus text

Never use colour alone: some users are colour-blind and phones are used in sunlight. Combine colour + icon + word for statuses like Paid, Pending and Failed.

Tip: a pill with 12 percent opacity background and full colour text works well in light and dark themes.
Widget status(String t, IconData i, Color c) => Container(
  padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
  decoration: BoxDecoration(color: c.withOpacity(0.12), borderRadius: BorderRadius.circular(20)),
  child: Row(mainAxisSize: MainAxisSize.min, children: [Icon(i, size: 16, color: c), const SizedBox(width: 4), Text(t, style: TextStyle(color: c, fontWeight: FontWeight.w600, fontSize: 13))]),
);
void main() {
  runApp(MaterialApp(home: Scaffold(
    appBar: AppBar(title: const Text('Fee status')),
    body: ListView(children: [
      ListTile(title: const Text('Ravi Kumar'), subtitle: const Text('Rs 1,500'), trailing: status('Paid', Icons.check_circle, Colors.green)),
      ListTile(title: const Text('Sunita Devi'), subtitle: const Text('Rs 1,500'), trailing: status('Pending', Icons.schedule, Colors.orange)),
      ListTile(title: const Text('Amit Oraon'), subtitle: const Text('Rs 1,500'), trailing: status('Overdue', Icons.error, Colors.red)),
    ]),
  )));
}

Animated explainer: Spacing relationships

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

Animated explainer: The four states of a list

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

The 12-point UI design checklist

1. One main action

Each screen has one obvious primary button. Everything else is quieter.

2. Spacing in steps of 8

Use 4, 8, 16, 24, 32. Same gap for same relationship.

3. Three text sizes

Title, body, caption. More than four sizes means a messy screen.

4. Colour with purpose

One brand colour, one accent. Red only for errors and danger.

5. Good contrast

Dark text on light, light text on dark. Use scheme on-colours.

6. Big tap targets

At least 48 by 48 pixels. Thumbs are not mouse pointers.

7. All states designed

Loading, empty, error, success. Not only the happy path.

8. Align and group

Left edges line up. Related things sit close together.

9. Consistent icons

One icon family and one size set across the app.

10. Works on small and big

Test with large text and on a narrow and a wide screen.

11. Dark mode ready

No hard-coded colours. Use Theme.of(context).

12. Real content

Test with real names, long text and real prices in Rs.

How to use it: before you show any screen to a client, tick all 12 boxes. Most bad screens fail on 1, 2 or 7.

Design process: from idea to polished screen

1. Understand

Who uses it? One line: "A Kanke Road dhaba owner who shows the menu on a tablet."

2. Sketch

Pen and paper, 3 versions of the main screen. Throw two away.

3. Build the skeleton

Layout only, grey boxes and real text. No colours yet.

4. Add the system

Theme, spacing and text styles from one place.

5. Add states

Loading, empty, error. Add a little motion.

6. Test with a person

Give the phone to someone and stay silent. Note where they hesitate.

Common mistake: picking colours and fonts first. Structure and spacing matter more than colour.
EASYReal project: cleaning up any crowded screenExample 1 of 10

Before and after: spacing

The same widgets twice. The right side uses padding, a gap and a bigger title. Nothing else changed.
Widget card(bool good) => Container(
  margin: EdgeInsets.all(good ? 12 : 2), padding: EdgeInsets.all(good ? 16 : 2),
  decoration: BoxDecoration(color: Colors.indigo.shade50, borderRadius: BorderRadius.circular(good ? 12 : 0)),
  child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
    Text('Fee due', style: TextStyle(fontSize: good ? 20 : 14, fontWeight: FontWeight.bold)),
    SizedBox(height: good ? 8 : 0),
    const Text('Rs 1,500 by 25 Nov'),
    SizedBox(height: good ? 12 : 0),
    FilledButton(onPressed: () {}, child: const Text('Pay')),
  ]),
);
void main() {
  runApp(MaterialApp(home: Scaffold(body: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [Expanded(child: Column(children: [const Padding(padding: EdgeInsets.only(top: 40), child: Text('Before')), card(false)])), Expanded(child: Column(children: [const Padding(padding: EdgeInsets.only(top: 40), child: Text('After')), card(true)]))]))));
}
Try it yourself: Make the After card even calmer with a 24 padding.
Edit the number in EdgeInsets.all.
EASYReal project: shop and menu appsExample 2 of 10

Product card hierarchy

Small label, big title, grey caption, bold price. Four sizes and colours create a clear reading order.
void main() {
  runApp(MaterialApp(home: Scaffold(body: Center(child: Card(margin: const EdgeInsets.all(24), child: Padding(padding: const EdgeInsets.all(20), child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [
    Container(height: 120, width: 240, decoration: BoxDecoration(color: Colors.orange.shade200, borderRadius: BorderRadius.circular(12)), child: const Icon(Icons.rice_bowl, size: 56, color: Colors.white)),
    const SizedBox(height: 12),
    const Text('BESTSELLER', style: TextStyle(fontSize: 11, fontWeight: FontWeight.bold, letterSpacing: 1.2, color: Colors.deepOrange)),
    const Text('Litti Chokha Thali', style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold)),
    const Text('Baked wheat balls with sattu, mashed brinjal and chutney', style: TextStyle(fontSize: 13, color: Colors.grey)),
    const SizedBox(height: 8),
    const Text('Rs 150', style: TextStyle(fontSize: 20, fontWeight: FontWeight.w700)),
  ]))))))); 
}
Try it yourself: Add a small veg icon beside the title.
A Row with an Icon and Text.
EASYReal project: orders, wishlist and search resultsExample 3 of 10

Empty state

Icon, headline, helper text and one action. The user learns what is missing and how to fix it.
void main() {
  runApp(MaterialApp(home: Scaffold(
    appBar: AppBar(title: const Text('Wishlist')),
    body: Center(child: Padding(padding: const EdgeInsets.all(32), child: Column(mainAxisSize: MainAxisSize.min, children: [
      Icon(Icons.favorite_border, size: 80, color: Colors.grey.shade400),
      const SizedBox(height: 16),
      const Text('Nothing saved yet', style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold)),
      const SizedBox(height: 8),
      const Text('Tap the heart on any product to save it here.', textAlign: TextAlign.center, style: TextStyle(color: Colors.grey)),
      const SizedBox(height: 20),
      FilledButton(onPressed: () {}, child: const Text('Browse products')),
    ]))),
  )));
}
Try it yourself: Design an empty state for a "No messages" screen.
Change icon and the three texts.
EASYReal project: any screen that loads dataExample 4 of 10

Error state with retry

Friendly words, no technical message, and a Retry button. Tapping Retry shows loading and then success.
class Page extends StatefulWidget {
  const Page({super.key});
  @override
  State<Page> createState() => _PageState();
}
class _PageState extends State<Page> {
  int s = 2;
  Future<void> retry() async {
    setState(() => s = 0);
    await Future.delayed(const Duration(seconds: 1));
    if (mounted) setState(() => s = 1);
  }
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Prices')),
    body: Center(child: s == 0 ? const CircularProgressIndicator() : s == 1 ? const Text('Rice Rs 52 per kg', style: TextStyle(fontSize: 22)) : Column(mainAxisSize: MainAxisSize.min, children: [
      const Icon(Icons.cloud_off, size: 72, color: Colors.red),
      const SizedBox(height: 12),
      const Text('Could not load prices', style: TextStyle(fontSize: 20)),
      const Text('Check your internet and try again.', style: TextStyle(color: Colors.grey)),
      const SizedBox(height: 16),
      FilledButton.icon(onPressed: retry, icon: const Icon(Icons.refresh), label: const Text('Try again')),
    ])),
  );
}
void main() => runApp(const MaterialApp(home: Page()));
Try it yourself: Fail the first retry and succeed the second.
Count attempts in a state variable.
EASYReal project: bottom bars and settings listsExample 5 of 10

Consistent icon set

Same size (24), same style (outlined), same colour rule. A mix of filled, round and sharp icons looks careless.
void main() {
  runApp(MaterialApp(home: Scaffold(
    appBar: AppBar(title: const Text('Settings')),
    body: ListView(children: const [
      ListTile(leading: Icon(Icons.person_outline), title: Text('Profile'), trailing: Icon(Icons.chevron_right)),
      ListTile(leading: Icon(Icons.notifications_none), title: Text('Notifications'), trailing: Icon(Icons.chevron_right)),
      ListTile(leading: Icon(Icons.lock_outline), title: Text('Privacy'), trailing: Icon(Icons.chevron_right)),
      ListTile(leading: Icon(Icons.help_outline), title: Text('Help'), trailing: Icon(Icons.chevron_right)),
    ]),
  )));
}
Try it yourself: Add a Language row with the same style.
Icons.language and a ListTile.
MEDIUMReal project: a dhaba or restaurant on Kanke RoadExample 6 of 10

Restaurant menu redesign

Category chips, cards with a clear price column and a veg dot. Local dish names. This is a typical client project.
class Dish {
  final String name, desc;
  final int price;
  final bool veg;
  const Dish(this.name, this.desc, this.price, this.veg);
}
class Menu extends StatefulWidget {
  const Menu({super.key});
  @override
  State<Menu> createState() => _MenuState();
}
class _MenuState extends State<Menu> {
  String cat = 'Mains';
  final data = const {
    'Mains': [Dish('Litti Chokha', 'Sattu stuffed, with chokha', 120, true), Dish('Chicken Handi', 'Slow cooked, Ranchi style', 260, false)],
    'Snacks': [Dish('Dhuska', 'Rice and dal fritter, with aloo dum', 50, true), Dish('Pittha', 'Steamed rice dumpling', 60, true)],
    'Sweets': [Dish('Thekua', 'Wheat and jaggery, festival favourite', 40, true)],
  };
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Dhaba Menu')),
    body: Column(children: [
      Padding(padding: const EdgeInsets.all(12), child: Row(children: [for (final c in data.keys) Padding(padding: const EdgeInsets.only(right: 8), child: ChoiceChip(label: Text(c), selected: cat == c, onSelected: (_) => setState(() => cat = c)))])),
      Expanded(child: ListView(padding: const EdgeInsets.symmetric(horizontal: 12), children: [
        for (final d in data[cat]!) Card(child: ListTile(
          leading: Icon(Icons.circle, size: 14, color: d.veg ? Colors.green : Colors.red),
          title: Text(d.name, style: const TextStyle(fontWeight: FontWeight.bold)),
          subtitle: Text(d.desc),
          trailing: Text('Rs ${d.price}', style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w700)),
        )),
      ])),
    ]),
  );
}
void main() => runApp(MaterialApp(theme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepOrange)), home: const Menu()));
Try it yourself: Add a Drinks category with Lassi and Chai.
Add a map entry with two Dish objects.
MEDIUMReal project: any app with preferencesExample 7 of 10

Grouped settings screen

Section titles, grouped tiles, a switch and a slider. Spacing between groups tells the user which settings belong together.
class Page extends StatefulWidget {
  const Page({super.key});
  @override
  State<Page> createState() => _PageState();
}
class _PageState extends State<Page> {
  bool notif = true, dark = false;
  double size = 16;
  Widget section(String t) => Padding(padding: const EdgeInsets.fromLTRB(16, 24, 16, 8), child: Text(t.toUpperCase(), style: TextStyle(fontSize: 12, fontWeight: FontWeight.bold, letterSpacing: 1.2, color: Theme.of(context).colorScheme.primary)));
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Settings')),
    body: ListView(children: [
      section('Account'),
      const ListTile(leading: Icon(Icons.person_outline), title: Text('Anita Kumari'), subtitle: Text('anita@ranchi.in')),
      section('Preferences'),
      SwitchListTile(secondary: const Icon(Icons.notifications_none), title: const Text('Notifications'), value: notif, onChanged: (v) => setState(() => notif = v)),
      SwitchListTile(secondary: const Icon(Icons.dark_mode_outlined), title: const Text('Dark mode'), value: dark, onChanged: (v) => setState(() => dark = v)),
      ListTile(leading: const Icon(Icons.text_fields), title: Text('Text size ${size.round()}'), subtitle: Slider(value: size, min: 12, max: 24, onChanged: (v) => setState(() => size = v))),
      section('About'),
      const ListTile(leading: Icon(Icons.info_outline), title: Text('Version 1.0.0')),
    ]),
  );
}
void main() => runApp(const MaterialApp(home: Page()));
Try it yourself: Add a Language group with Hindi and English radio choices.
RadioListTile with groupValue.
MEDIUMReal project: first-run screens of any appExample 8 of 10

Three-page onboarding

PageView with a big icon, a title and a short line per page, plus dots that grow for the current page. Skip and Next buttons end the intro.
class Intro extends StatefulWidget {
  const Intro({super.key});
  @override
  State<Intro> createState() => _IntroState();
}
class _IntroState extends State<Intro> {
  final pc = PageController();
  int page = 0;
  final pages = const [
    [Icons.storefront, 'Find shops near you', 'Kirana, sweets, vegetables, all around Ranchi.'],
    [Icons.delivery_dining, 'Fast delivery', 'Within 45 minutes in Ranchi city.'],
    [Icons.payments, 'Pay your way', 'UPI, card or cash on delivery.'],
  ];
  @override
  Widget build(BuildContext context) => Scaffold(
    body: SafeArea(child: Column(children: [
      Align(alignment: Alignment.centerRight, child: TextButton(onPressed: () {}, child: const Text('Skip'))),
      Expanded(child: PageView(controller: pc, onPageChanged: (i) => setState(() => page = i), children: [
        for (final p in pages) Padding(padding: const EdgeInsets.all(32), child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
          Icon(p[0] as IconData, size: 110, color: Theme.of(context).colorScheme.primary),
          const SizedBox(height: 24),
          Text(p[1] as String, style: const TextStyle(fontSize: 26, fontWeight: FontWeight.bold)),
          const SizedBox(height: 8),
          Text(p[2] as String, textAlign: TextAlign.center, style: const TextStyle(fontSize: 16, color: Colors.grey)),
        ])),
      ])),
      Row(mainAxisAlignment: MainAxisAlignment.center, children: [for (var i = 0; i < pages.length; i++) AnimatedContainer(duration: const Duration(milliseconds: 250), margin: const EdgeInsets.all(4), width: i == page ? 24 : 8, height: 8, decoration: BoxDecoration(color: i == page ? Theme.of(context).colorScheme.primary : Colors.grey.shade300, borderRadius: BorderRadius.circular(4)))]),
      Padding(padding: const EdgeInsets.all(20), child: SizedBox(width: double.infinity, child: FilledButton(onPressed: () { if (page < 2) { pc.nextPage(duration: const Duration(milliseconds: 300), curve: Curves.easeOut); } }, child: Text(page < 2 ? 'Next' : 'Get started')))),
    ])),
  );
}
void main() => runApp(const MaterialApp(home: Intro()));
Try it yourself: Add a fourth page about offers.
Add a list entry. The dots follow pages.length.
HARDReal project: a Ranchi grocery or fashion store appExample 9 of 10

Shop home screen redesign

A realistic home screen: search bar, offer banner, category chips, and a product grid with price and a heart. Combines spacing, type, theme, grid, clip and state from the whole course.
class Home extends StatefulWidget {
  const Home({super.key});
  @override
  State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
  final fav = <int>{};
  String cat = 'All';
  final items = const [['Basmati rice 5 kg', 420], ['Mustard oil 1 L', 165], ['Tea Assam 500 g', 240], ['Atta 10 kg', 390], ['Jaggery 1 kg', 70], ['Sattu 500 g', 60]];
  @override
  Widget build(BuildContext context) {
    final cs = Theme.of(context).colorScheme;
    return Scaffold(
      appBar: AppBar(title: const Text('Ranchi Mart'), actions: [IconButton(icon: const Icon(Icons.shopping_cart_outlined), onPressed: () {})]),
      body: ListView(padding: const EdgeInsets.all(16), children: [
        SearchBar(hintText: 'Search groceries', leading: const Icon(Icons.search)),
        const SizedBox(height: 16),
        ClipRRect(borderRadius: BorderRadius.circular(16), child: Container(height: 110, padding: const EdgeInsets.all(20), decoration: BoxDecoration(gradient: LinearGradient(colors: [cs.primary, cs.tertiary])), child: const Column(crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [
          Text('Festival offer', style: TextStyle(color: Colors.white70)),
          Text('Flat 15% off on staples', style: TextStyle(color: Colors.white, fontSize: 22, fontWeight: FontWeight.bold)),
        ]))),
        const SizedBox(height: 16),
        Wrap(spacing: 8, children: [for (final c in ['All', 'Staples', 'Snacks', 'Dairy']) ChoiceChip(label: Text(c), selected: cat == c, onSelected: (_) => setState(() => cat = c))]),
        const SizedBox(height: 16),
        GridView.count(shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), crossAxisCount: 2, childAspectRatio: 0.85, mainAxisSpacing: 12, crossAxisSpacing: 12, children: [
          for (var i = 0; i < items.length; i++) Card(clipBehavior: Clip.antiAlias, child: Padding(padding: const EdgeInsets.all(12), child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
            Expanded(child: Container(width: double.infinity, decoration: BoxDecoration(color: cs.primaryContainer, borderRadius: BorderRadius.circular(10)), child: Icon(Icons.shopping_basket, size: 40, color: cs.onPrimaryContainer))),
            const SizedBox(height: 8),
            Text(items[i][0] as String, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(fontWeight: FontWeight.w600)),
            Row(children: [Text('Rs ${items[i][1]}', style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), const Spacer(), InkWell(onTap: () => setState(() => fav.contains(i) ? fav.remove(i) : fav.add(i)), child: Icon(fav.contains(i) ? Icons.favorite : Icons.favorite_border, color: fav.contains(i) ? Colors.red : Colors.grey, size: 22))]),
          ]))),
        ]),
      ]),
    );
  }
}
void main() => runApp(MaterialApp(theme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.green)), home: const Home()));
Try it yourself: Show how many hearts are saved in the AppBar.
Text(fav.length.toString()) in actions.
HARDReal project: doctor, salon and coaching bookingsExample 10 of 10

Clinic appointment booking flow

A date strip, time slot chips, a summary card that updates as you choose, and a confirm button that is disabled until both are picked. Then a success dialog. A complete flow with all states.
class Book extends StatefulWidget {
  const Book({super.key});
  @override
  State<Book> createState() => _BookState();
}
class _BookState extends State<Book> {
  int? day;
  String? slot;
  final days = ['Mon 24', 'Tue 25', 'Wed 26', 'Thu 27', 'Fri 28'];
  final slots = ['10:00', '10:30', '11:00', '11:30', '4:00', '4:30'];
  final taken = {'10:30', '4:00'};
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Book appointment')),
    body: Padding(padding: const EdgeInsets.all(16), child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      const Card(child: ListTile(leading: CircleAvatar(child: Icon(Icons.medical_services)), title: Text('Dr. Meena Sinha'), subtitle: Text('Dental clinic, Lalpur - Rs 400'))),
      const SizedBox(height: 16),
      const Text('Pick a day', style: TextStyle(fontWeight: FontWeight.bold)),
      const SizedBox(height: 8),
      Wrap(spacing: 8, children: [for (var i = 0; i < days.length; i++) ChoiceChip(label: Text(days[i]), selected: day == i, onSelected: (_) => setState(() => day = i))]),
      const SizedBox(height: 16),
      const Text('Pick a time', style: TextStyle(fontWeight: FontWeight.bold)),
      const SizedBox(height: 8),
      Wrap(spacing: 8, runSpacing: 8, children: [for (final s in slots) ChoiceChip(label: Text(s), selected: slot == s, onSelected: taken.contains(s) ? null : (_) => setState(() => slot = s))]),
      const Spacer(),
      if (day != null && slot != null) Card(color: Theme.of(context).colorScheme.primaryContainer, child: Padding(padding: const EdgeInsets.all(12), child: Text('${days[day!]} Nov at $slot'))),
      const SizedBox(height: 8),
      SizedBox(width: double.infinity, child: FilledButton(
        onPressed: day != null && slot != null ? () => showDialog(context: context, builder: (c) => AlertDialog(icon: const Icon(Icons.check_circle, color: Colors.green, size: 48), title: const Text('Booked!'), content: Text('See you on ${days[day!]} at $slot.'), actions: [TextButton(onPressed: () => Navigator.pop(c), child: const Text('Done'))])) : null,
        child: const Text('Confirm booking'),
      )),
    ])),
  );
}
void main() => runApp(MaterialApp(theme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal)), home: const Book()));
Try it yourself: Add a note field and show it in the success dialog.
TextEditingController in state; read in the dialog.

Quick quiz

3 questions. Click an answer.
Which set follows an 8-point spacing system?
4, 8, 16, 245, 11, 17, 233, 7, 13, 1910, 15, 22, 31
Besides the list itself, a list screen should design:
Loading, empty and error statesOnly the coloursOnly the iconsNothing else
Why add an icon and text to a red or green status?
Colour alone is not enough for everyoneIt looks more complicatedFlutter requires itIt saves memory
Score: 0 / 3

Recap: what you learned in Module 36

Spacing

4, 8, 16, 24, 32 in constants.

Type

Title, body, caption.

States

Loading, empty, error, success.

Redesign

Menu, shop, booking screens.

Checklist

12 points before every demo.

Portfolio

Before and after plus reasons.

Next: the next part of the course.

Capstone: your design portfolio

Project 1: Dhaba menu app

Menu cards, categories, dark mode. Client: a restaurant on Kanke Road.

Project 2: Coaching centre app

Dashboard, fee status, attendance chart. Client: a coaching centre in Ranchi.

Project 3: Local shop catalogue

Responsive grid, search, cart sheet. Client: a kirana or cloth store.

Project 4: Clinic booking

Date and time picker, confirmation flow, empty and error states.

Project 5: Fitness tracker

Progress rings, weekly bar chart, animated streak counter.

Project 6: Your own idea

Pick a business you know. Design 5 screens, build them in Flutter, put screenshots in a README.

What to show: before and after screenshots, the theme file, and a one-line reason for each design choice. Employers read the reasons.

Career: UI-focused Flutter work

Roles

Flutter UI developer, mobile app developer, front-end developer, UI engineer. Many startups in Ranchi, Patna, Kolkata and Bengaluru hire for UI polish.

Freelance

Redesign screens for local shops and schools. Offer a fixed-price "app makeover" for Rs 8,000 to 25,000.

Grow into

Design systems, accessibility, animation, Flutter web and desktop, and learning basic Figma to talk with designers.

Portfolio

Six finished screens or apps, before-and-after images, a live web demo and a GitHub README.

Interview questions

Constraints and layout, keys, Theme.of, LayoutBuilder vs MediaQuery, how to avoid jank, how to test widgets.

Keep learning

Read the Material 3 guidelines, rebuild one popular app screen each week, and study open-source Flutter apps.

Click the name to edit it, then press Ctrl+P to print or save as PDF.
BRAINBIT INFOTECH, RANCHI
Certificate of Completion
This is to certify that
Your Name Here
has successfully completed the
Flutter Widgets and Design Course
16 modules, 160 practical examples, 6 portfolio projects
Date
🏆
Nandan Kumar, Trainer

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