Define Colors class in flutter project

ariba.dev
2 min readOct 29, 2024

--

Defining an AppColors class in a Flutter project is a great way to manage your color palette consistently across your app. Here’s how you can do it:

  1. Create a Colors File: First, create a new Dart file, usually named app_colors.dart in your lib directory (you might want to create a styles or theme folder for better organization).
  2. Define the Class: Inside app_colors.dart, define a class that contains your color constants.

Here’s an example:

import 'package:flutter/material.dart';

class AppColors {
// Primary colors
static const Color primary = Color(0xFF6200EA);
static const Color primaryVariant = Color(0xFF3700B3);
static const Color secondary = Color(0xFF03DAC6);
static const Color secondaryVariant = Color(0xFF018786);

// Background colors
static const Color background = Color(0xFFF5F5F5);
static const Color surface = Color(0xFFFFFFFF);

// Error color
static const Color error = Color(0xFFB00020);

// Text colors
static const Color onPrimary = Color(0xFFFFFFFF);
static const Color onSecondary = Color(0xFF000000);
static const Color onBackground = Color(0xFF000000);
static const Color onSurface = Color(0xFF000000);
static const Color onError = Color(0xFFFFFFFF);
}

3. Using the AppColors Class: You can then use these color constants in your widgets.

For example:

import 'app_colors.dart';

class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
color: AppColors.primary,
child: Text(
'Hello, Flutter!',
style: TextStyle(color: AppColors.onPrimary),
),
);
}
}

4. ThemeData: You can also integrate AppColors into your app’s theme for a more consistent approach:

import 'app_colors.dart';

final ThemeData appTheme = ThemeData(
primaryColor: AppColors.primary,
accentColor: AppColors.secondary,
backgroundColor: AppColors.background,
errorColor: AppColors.error,
textTheme: TextTheme(
bodyText1: TextStyle(color: AppColors.onBackground),
// Add more text styles as needed
),
);

5. Apply the Theme: Finally, apply your theme in the MaterialApp widget:

void main() {
runApp(
MaterialApp(
theme: appTheme,
home: MyHomePage(),
),
);
}

This approach keeps your color management organized and makes it easy to make changes globally throughout your app.

--

--

ariba.dev
ariba.dev

Written by ariba.dev

⚡Dart makes my heart Flutter 💙🧑‍💻 • ✨ Software developer🧑‍💻 • Looking for the best remote opportunity in EUROPE

No responses yet