Flutter: Material Design and Common Components
Material Design is Flutter's native language — master it and your app will have platform-consistent "native feel."
📋 Prerequisites: You need to have completed the following first
- Lesson 5: StatefulWidget and Interaction
1. What You Will Learn
- Scaffold global scaffold: AppBar / BottomNavigationBar / FloatingActionButton / Drawer
- Cards and lists: Card, ListTile, Divider
- Dialogs: AlertDialog, BottomSheet, Snackbar
- Toggle components: Switch, Checkbox, Radio, Slider
- ShopApp product detail page: SliverAppBar + BottomSheet size selection
2. A Story from Design Specs to Code
(1) The Pain: Building UI Components from Scratch Is Time-Consuming
Bob received the ShopApp UI design specs and found that 80% of the components are standard Material Design: AppBar, Card, FAB, BottomSheet. If he hand-coded each one, it would take an estimated 3 weeks of development. Worse, his custom components didn't match the system's native style, and users complained the app "didn't look like a proper app."
(2) The Material Component Library Solution
Flutter includes a complete Material Design component library — use standard components with a single line of code, with built-in animations, accessibility, and theme adaptation.
import 'package:flutter/material.dart';
// 5 lines = full Material page
Scaffold(
appBar: AppBar(title: const Text('ShopApp')),
body: const ProductList(),
floatingActionButton: FloatingActionButton(onPressed: () {}, child: const Icon(Icons.add)),
bottomNavigationBar: BottomNavigationBar(items: [...]),
)
> Output: Run locally with Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly across platforms.
(3) The Result: 3x Development Speed Improvement
After using Material components, the detail page went from 3 days to 1 day, with automatic Light/Dark theme and accessibility mode adaptation.
3. Scaffold
Scaffold is the foundational framework for Material Design pages, providing a standardized page structure.
graph TD
S[Scaffold] --> A[AppBar]
S --> B[Body]
S --> F[FAB]
S --> BN[BottomNavigationBar]
S --> D[Drawer]
B --> C[Card]
B --> LT[ListTile]
B --> GV[GridView]
> Output: Run locally with Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly across platforms.
(1) Scaffold Components
| Property | Type | Description |
|---|---|---|
appBar |
PreferredSizeWidget | Top navigation bar |
body |
Widget | Page body |
floatingActionButton |
Widget | Bottom-right floating button |
bottomNavigationBar |
Widget | Bottom navigation bar |
drawer |
Widget | Left drawer menu |
bottomSheet |
Widget | Bottom popup panel |
snackBar |
SnackBar | Bottom notification bar |
▶ Example
> Output: Run locally with Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly across platforms.
: ShopApp home page Scaffold
import 'package:flutter/material.dart';
Scaffold(
appBar: AppBar(
title: const Text('ShopApp'),
actions: [
IconButton(icon: const Icon(Icons.search), onPressed: () {}),
IconButton(icon: const Icon(Icons.shopping_cart), onPressed: () {}),
],
),
body: const ProductGrid(),
floatingActionButton: FloatingActionButton.extended(
onPressed: () {},
icon: const Icon(Icons.flash_on),
label: const Text('Flash Sale'),
),
bottomNavigationBar: NavigationBar(
destinations: const [
NavigationDestination(icon: Icon(Icons.home), label: 'Home'),
NavigationDestination(icon: Icon(Icons.category), label: 'Categories'),
NavigationDestination(icon: Icon(Icons.favorite), label: 'Wishlist'),
NavigationDestination(icon: Icon(Icons.person), label: 'Profile'),
],
),
drawer: Drawer(
child: ListView(
children: [
const DrawerHeader(
decoration: BoxDecoration(color: Colors.blue),
child: Text('ShopApp', style: TextStyle(color: Colors.white, fontSize: 24)),
),
ListTile(leading: const Icon(Icons.home), title: const Text('Home'), onTap: () {}),
ListTile(leading: const Icon(Icons.settings), title: const Text('Settings'), onTap: () {}),
],
),
),
)
> Output: Run locally with Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly across platforms.
4. Card and List Components
(1) Card and ListTile
▶ Example
> Output: Run locally with Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly across platforms.
: Product card (Card + ListTile)
import 'package:flutter/material.dart';
// Simplified class definition
class Product {
final String imageUrl;
final String name;
final double price;
final String category;
const Product({required this.imageUrl, required this.name, required this.price, required this.category});
}
Card(
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
elevation: 2,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
child: ListTile(
leading: ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Image.network(product.imageUrl, width: 56, height: 56, fit: BoxFit.cover),
),
title: Text(product.name, style: const TextStyle(fontWeight: FontWeight.w600)),
subtitle: Text('$${product.price.toStringAsFixed(2)} - ${product.category}'),
trailing: IconButton(
icon: const Icon(Icons.add_shopping_cart),
onPressed: () => addToCart(product),
),
onTap: () => navigateToDetail(product),
),
)
> Output: Run locally with Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly across platforms.
▶ Example
> Output: Run locally with Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly across platforms.
: Order list (ListTile + Divider)
import 'package:flutter/material.dart';
// Simplified class definition
class Order {
final int id;
final double total;
final String date;
final String status;
const Order({required this.id, required this.total, required this.date, required this.status});
}
ListView.separated(
itemCount: orders.length,
separatorBuilder: (_, __) => const Divider(height: 1, indent: 16),
itemBuilder: (context, index) {
final order = orders[index];
return ListTile(
leading: CircleAvatar(
backgroundColor: order.status == 'Shipped' ? Colors.green : Colors.orange,
child: Icon(order.status == 'Shipped' ? Icons.local_shipping : Icons.schedule,
color: Colors.white),
),
title: Text('Order #${order.id}'),
subtitle: Text('$${order.total.toStringAsFixed(2)} - ${order.date}'),
trailing: const Icon(Icons.chevron_right),
onTap: () => navigateToOrderDetail(order),
);
},
)
> Output: Run locally with Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly across platforms.
5. Dialog Components
(1) Dialog Types Comparison
| Component | Position | Interaction | Use Case |
|---|---|---|---|
| AlertDialog | Center popup | Confirm/Cancel | Important action confirmation (delete order) |
| BottomSheet | Slides up from bottom | Custom content | Size selection, filtering |
| Snackbar | Bottom temporary notification | Can include action | Lightweight feedback (added to cart) |
| Dialog | Center popup | Fully customizable | Custom popup content |
▶ Example
> Output: Run locally with Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly across platforms.
: Delete confirmation AlertDialog
import 'package:flutter/material.dart';
// Simplified class definition
class CartItem {
final String name;
const CartItem({required this.name});
}
void showDeleteConfirmation(BuildContext context, CartItem item) {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('Remove Item'),
content: Text('Remove "${item.name}" from your cart?'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
FilledButton(
onPressed: () {
removeItem(item);
Navigator.pop(context);
},
child: const Text('Remove'),
),
],
),
);
}
> Output: Run locally with Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly across platforms.
▶ Example
> Output: Run locally with Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly across platforms.
: Size selection BottomSheet
import 'package:flutter/material.dart';
// Product class definition shown above
void showSizeSelector(BuildContext context, Product product) {
showModalBottomSheet(
context: context,
isScrollControlled: true,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
),
builder: (context) => DraggableScrollableSheet(
initialChildSize: 0.5,
minChildSize: 0.3,
maxChildSize: 0.8,
expand: false,
builder: (context, scrollController) => Column(
children: [
// Handle bar
Center(child: Container(
margin: const EdgeInsets.symmetric(vertical: 8),
width: 40, height: 4,
decoration: BoxDecoration(color: Colors.grey[300], borderRadius: BorderRadius.circular(2)),
)),
Padding(
padding: const EdgeInsets.all(16),
child: Text('Select Size', style: Theme.of(context).textTheme.titleLarge),
),
Expanded(
child: ListView(
controller: scrollController,
children: ['S', 'M', 'L', 'XL', 'XXL'].map((size) => ListTile(
title: Text('Size $size'),
trailing: size == 'M' ? const Icon(Icons.check, color: Colors.green) : null,
onTap: () => Navigator.pop(context, size),
)).toList(),
),
),
],
),
),
);
}
> Output: Run locally with Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly across platforms.
▶ Example
> Output: Run locally with Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly across platforms.
: Cart Snackbar feedback
import 'package:flutter/material.dart';
// Product class definition shown above
void showCartSnackbar(BuildContext context, Product product) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('${product.name} added to cart'),
duration: const Duration(seconds: 2),
action: SnackBarAction(
label: 'View Cart',
onPressed: () => navigateToCart(),
),
),
);
}
> Output: Run locally with Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly across platforms.
6. Toggle Components
(1) Toggle Components Comparison
| Component | Interaction | Data Type | Use Case |
|---|---|---|---|
| Switch | Slide toggle | bool |
On/off settings (dark mode) |
| Checkbox | Click to check | bool |
Multi-select confirmation (agree to terms) |
| Radio | Click for single selection | T |
Single selection from a group (payment method) |
| Slider | Drag slider | double |
Range selection (price range) |
▶ Example
> Output: Run locally with Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly across platforms.
: Payment method radio selection
import 'package:flutter/material.dart';
class PaymentSelector extends StatefulWidget {
const PaymentSelector({super.key});
@override
State<PaymentSelector> createState() => _PaymentSelectorState();
}
class _PaymentSelectorState extends State<PaymentSelector> {
String _payment = 'credit_card';
@override
Widget build(BuildContext context) {
return Column(
children: [
RadioListTile<String>(
title: const Text('Credit Card'),
subtitle: const Text('Visa **** 4242'),
secondary: const Icon(Icons.credit_card),
value: 'credit_card',
groupValue: _payment,
onChanged: (v) => setState(() => _payment = v!),
),
RadioListTile<String>(
title: const Text('PayPal'),
secondary: const Icon(Icons.account_balance_wallet),
value: 'paypal',
groupValue: _payment,
onChanged: (v) => setState(() => _payment = v!),
),
RadioListTile<String>(
title: const Text('Apple Pay'),
secondary: const Icon(Icons.phone_iphone),
value: 'apple_pay',
groupValue: _payment,
onChanged: (v) => setState(() => _payment = v!),
),
],
);
}
}
> Output: Run locally with Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly across platforms.
▶ Example
> Output: Run locally with Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly across platforms.
: Price range Slider
import 'package:flutter/material.dart';
RangeValues _priceRange = const RangeValues(0, 500);
RangeSlider(
values: _priceRange,
min: 0,
max: 2000,
divisions: 40,
labels: RangeLabels(
'$${_priceRange.start.toStringAsFixed(0)}',
'$${_priceRange.end.toStringAsFixed(0)}',
),
onChanged: (values) => setState(() => _priceRange = values),
)
> Output: Run locally with Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly across platforms.
7. Complete Example: ShopApp Product Detail Page
import 'package:flutter/material.dart';
// Simplified class definition
class Product {
final String name;
final double price;
final String imageUrl;
final double? originalPrice;
final double rating;
final int reviewCount;
const Product({required this.name, required this.price, required this.imageUrl, this.originalPrice, this.rating = 0.0, this.reviewCount = 0});
}
class ProductDetailPage extends StatelessWidget {
final Product product;
const ProductDetailPage({super.key, required this.product});
@override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
slivers: [
// Collapsible app bar with product image
SliverAppBar(
expandedHeight: 300,
pinned: true,
flexibleSpace: FlexibleSpaceBar(
title: Text(product.name, style: const TextStyle(fontSize: 16)),
background: Stack(
fit: StackFit.expand,
children: [
Image.network(product.imageUrl, fit: BoxFit.cover),
const DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(begin: Alignment.bottomCenter, end: Alignment.topCenter,
colors: [Colors.black54, Colors.transparent]),
),
),
],
),
),
),
// Product info
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(children: [
Text('$${product.price.toStringAsFixed(2)}',
style: const TextStyle(fontSize: 28, fontWeight: FontWeight.bold, color: Colors.green)),
const SizedBox(width: 12),
if (product.originalPrice != null)
Text('$${product.originalPrice!.toStringAsFixed(2)}',
style: const TextStyle(decoration: TextDecoration.lineThrough, color: Colors.grey)),
]),
const SizedBox(height: 8),
Row(children: [
Icon(Icons.star, color: Colors.amber[700], size: 18),
Text(' ${product.rating} (${product.reviewCount} reviews)'),
]),
const SizedBox(height: 16),
const Text('Description', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600)),
const SizedBox(height: 8),
const Text('Premium quality product with fast shipping worldwide. '
'Free returns within 30 days. USD settlement supported.'),
],
),
),
),
],
),
// Bottom action bar
bottomNavigationBar: SafeArea(
child: Padding(
padding: const EdgeInsets.all(12),
child: Row(children: [
IconButton.outlined(onPressed: () {}, icon: const Icon(Icons.favorite_border)),
const SizedBox(width: 8),
Expanded(
child: FilledButton.icon(
onPressed: () => _showSizeSelector(context),
icon: const Icon(Icons.shopping_cart),
label: const Text('Add to Cart'),
),
),
]),
),
),
);
}
void _showSizeSelector(BuildContext context) {
showModalBottomSheet(
context: context,
builder: (ctx) => const SizeSelectorSheet(),
);
}
}
> Output: Run locally with Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly across platforms.
❓ FAQ
ScaffoldMessenger.of(context).showSnackBar() using the Scaffold's context. If you use a Builder or nested Scaffold, the context might be wrong.shape property: shape: RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(20))).📖 Summary
- Scaffold provides the standard Material Design page structure: AppBar + Body + FAB + BottomNav + Drawer
- Card + ListTile quickly builds list items, Divider separates them
- AlertDialog for confirmation actions, BottomSheet for complex selections, Snackbar for lightweight feedback
- Switch/Checkbox/Radio/Slider cover all toggle scenarios
- SliverAppBar creates collapsible headers, combined with CustomScrollView for immersive detail pages
📝 Exercises
- Basic (difficulty ⭐): Create a Scaffold with a Drawer containing 5 menu items (Home/Cart/Orders/Settings/About).
- Intermediate (difficulty ⭐⭐): Implement a BottomSheet filter panel with a price Slider and category Checkboxes, showing filter results via Snackbar after confirming.
- Challenge (difficulty ⭐⭐⭐): Implement a complete product detail page: SliverAppBar with collapsible image + product info + size selection BottomSheet + add-to-cart Snackbar feedback.