Question #323EasyWidgets & UI

What is a Theme in Flutter?

#theme#styling#design

Answer

Overview

A

text
Theme
in Flutter is a set of shared visual properties (colors, fonts, shapes, sizes) that apply to all widgets in an app or widget subtree. It enables consistent styling without repeating yourself.


Setting Theme in MaterialApp

dart
MaterialApp(
  theme: ThemeData(
    // Color scheme
    colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
    useMaterial3: true,

    // Text styles
    textTheme: TextTheme(
      headlineLarge: TextStyle(fontSize: 32, fontWeight: FontWeight.bold),
      bodyMedium: TextStyle(fontSize: 14, color: Colors.grey[700]),
    ),

    // AppBar theme
    appBarTheme: AppBarTheme(
      backgroundColor: Colors.deepPurple,
      foregroundColor: Colors.white,
      elevation: 0,
    ),

    // Button theme
    elevatedButtonTheme: ElevatedButtonThemeData(
      style: ElevatedButton.styleFrom(
        backgroundColor: Colors.deepPurple,
        foregroundColor: Colors.white,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
      ),
    ),

    // Input field theme
    inputDecorationTheme: InputDecorationTheme(
      border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
    ),
  ),
  home: HomeScreen(),
)

Dark Theme

dart
MaterialApp(
  theme: ThemeData.light(),
  darkTheme: ThemeData.dark(),
  themeMode: ThemeMode.system, // Follows device setting
  home: HomeScreen(),
)
dart
// ThemeMode options:
ThemeMode.system  // Auto (follows OS)
ThemeMode.light   // Always light
ThemeMode.dark    // Always dark

Accessing Theme in Widgets

dart
Widget build(BuildContext context) {
  final theme = Theme.of(context);

  return Column(
    children: [
      Text(
        'Hello',
        style: theme.textTheme.headlineLarge, // Use theme text style
      ),
      Container(
        color: theme.colorScheme.primaryContainer, // Use theme color
        child: Icon(Icons.star, color: theme.colorScheme.primary),
      ),
    ],
  );
}

Override Theme for a Sub-tree

dart
// Apply a different theme to just one part of the widget tree
Theme(
  data: Theme.of(context).copyWith(
    iconTheme: IconThemeData(color: Colors.red, size: 32),
  ),
  child: Row(
    children: [
      Icon(Icons.star),   // Red, size 32
      Icon(Icons.heart),  // Red, size 32
    ],
  ),
)

Useful Theme Properties

PropertyControls
text
colorScheme
All colors (primary, secondary, surface, error)
text
textTheme
Text styles (headline, body, label, etc.)
text
appBarTheme
AppBar styling
text
cardTheme
Card styling
text
elevatedButtonTheme
ElevatedButton styling
text
inputDecorationTheme
TextField/TextFormField styling
text
iconTheme
Icon color and size
text
dividerTheme
Divider color and thickness

Best Practice: Define your full

text
ThemeData
once in
text
MaterialApp
and use
text
Theme.of(context)
to access colors/styles throughout your app. Avoid hardcoding colors — always pull from the theme.