How to Change Primary Color in Flutter: Simple Guide
To change the primary color in Flutter, set the
primaryColor property inside ThemeData in your MaterialApp widget. This updates the main color used throughout your app's UI components.Syntax
The primary color is set inside the ThemeData object, which you pass to the theme property of MaterialApp. The key part is:
primaryColor: Defines the main color used by many widgets.
dart
MaterialApp(
theme: ThemeData(
primaryColor: Colors.blue,
),
home: MyHomePage(),
)Example
This example shows a simple Flutter app with the primary color set to green. The app bar and other widgets that use the primary color will appear green.
dart
import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Primary Color Demo', theme: ThemeData( primaryColor: Colors.green, ), home: const MyHomePage(), ); } } class MyHomePage extends StatelessWidget { const MyHomePage({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Home Page'), ), body: const Center( child: Text('Primary color is green!'), ), ); } }
Output
A Flutter app with a green app bar and text 'Primary color is green!' centered on screen.
Common Pitfalls
Common mistakes when changing the primary color include:
- Setting
primaryColorbut not rebuilding the app, so changes don't show. - Using
colorproperties directly on widgets instead of relying on the theme, causing inconsistent colors. - Confusing
primaryColorwithcolorScheme.primary, which is the newer recommended way.
For newer Flutter versions, prefer using colorScheme inside ThemeData for better theming control.
dart
/* Wrong way: */ MaterialApp( theme: ThemeData( primaryColor: Colors.red, ), home: Scaffold( appBar: AppBar( backgroundColor: Colors.blue, // overrides primaryColor title: Text('Wrong Example'), ), ), ) /* Right way: */ MaterialApp( theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.red), useMaterial3: true, ), home: Scaffold( appBar: AppBar( title: Text('Right Example'), ), ), )
Quick Reference
Summary tips for changing primary color in Flutter:
- Use
ThemeData(primaryColor: yourColor)for basic theming. - Prefer
colorSchemewithColorScheme.fromSeedfor modern apps. - Apply colors consistently by using theme colors instead of hardcoded widget colors.
- Rebuild your app after changing theme to see updates.
Key Takeaways
Set primary color in ThemeData inside MaterialApp to change app's main color.
Use colorScheme with ColorScheme.fromSeed for modern, consistent theming.
Avoid hardcoding colors on widgets; rely on theme colors for consistency.
Rebuild the app after changing theme to apply updates.
AppBar and many widgets automatically use the primary color from the theme.