0
0
FlutterHow-ToBeginner · 3 min read

How to Use Theme in Flutter for Consistent UI Design

In Flutter, you use ThemeData inside a MaterialApp to define colors, fonts, and styles globally. Access the theme in widgets with Theme.of(context) to keep your app's look consistent.
📐

Syntax

The main way to use themes in Flutter is by setting the theme property of MaterialApp with a ThemeData object. Inside ThemeData, you define colors, text styles, and other UI properties.

Use Theme.of(context) inside widgets to get the current theme and apply its styles.

dart
MaterialApp(
  theme: ThemeData(
    primaryColor: Colors.blue,
    textTheme: TextTheme(
      bodyText1: TextStyle(color: Colors.black, fontSize: 16),
    ),
  ),
  home: MyHomePage(),
)
💻

Example

This example shows how to set a theme with a primary color and text style, then use the theme colors and text styles inside a widget.

dart
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primaryColor: Colors.teal,
        textTheme: TextTheme(
          bodyText1: TextStyle(color: Colors.teal.shade900, fontSize: 18),
        ),
      ),
      home: Scaffold(
        appBar: AppBar(title: Text('Theme Example')),
        body: Center(
          child: Builder(
            builder: (context) => Text(
              'Hello with Theme!',
              style: Theme.of(context).textTheme.bodyText1,
            ),
          ),
        ),
      ),
    );
  }
}
Output
A screen with a teal app bar titled 'Theme Example' and centered text 'Hello with Theme!' in teal color and font size 18.
⚠️

Common Pitfalls

  • Not wrapping your app in MaterialApp or missing the theme property means no global theme is applied.
  • Using hardcoded colors or styles inside widgets instead of Theme.of(context) breaks consistency.
  • Forgetting to rebuild widgets after changing the theme can cause UI not to update.
dart
/* Wrong: hardcoded color */
Text('Hi', style: TextStyle(color: Colors.red))

/* Right: use theme color */
Text('Hi', style: Theme.of(context).textTheme.bodyText1)
📊

Quick Reference

  • MaterialApp.theme: Set your app's theme.
  • ThemeData: Define colors, fonts, and styles.
  • Theme.of(context): Access current theme inside widgets.
  • primaryColor: Main color for app bars and accents.
  • textTheme: Define text styles for your app.

Key Takeaways

Set your app theme in MaterialApp using ThemeData for consistent styling.
Use Theme.of(context) inside widgets to apply theme colors and text styles.
Avoid hardcoding colors or fonts to keep your UI consistent and easy to update.
Remember to rebuild widgets to reflect theme changes.
Use primaryColor and textTheme in ThemeData to control main colors and fonts.