The Ultimate Guide to Handling Colors and Gradients in Flutter Production Apps

In this article, we learn how to handle Flutter colors like a pro in production-level development by storing all colors in one place for easy debugging and bug fixes. 

We create a class called AppColor with a private constructor and store all the colors and gradients used in our app as static const properties. Using this method, debugging becomes easier and bug fixes require only a single commit, reducing the chances of merge conflicts.


Usage:

To handle Flutter colors like a pro in your app, create a dart file called colors.dart in the constants folder and define a class called AppColor with a private constructor. 

Store all colors and gradients used in your app as static const properties within the class. 

To use a color or gradient, reference it as AppColor.propertyName.


Code:

import 'package:flutter/material.dart';

class AppColor {
  AppColor._(); // Private constructor to prevent instantiation

  static const Color primaryColor = Color(0xFF2F39C5);
  static const Color secondaryColor = Color(0xFFFF9A9E);
  static const Color accentColor = Color(0xFFE0C3FC);

  static const Gradient linearGradient = LinearGradient(
    begin: Alignment.topLeft,
    end: Alignment.bottomRight,
    colors: [
      primaryColor,
      secondaryColor,
    ],
  );

  static const Gradient radialGradient = RadialGradient(
    center: Alignment.center,
    radius: 0.75,
    colors: [
      accentColor,
      secondaryColor,
    ],
  );
}

..

You can use these colors and gradients in your widgets like this:

Container(
  color: AppColor.primaryColor, // Use the primaryColor property
  child: Text(
    'Hello World',
    style: TextStyle(
      color: AppColor.secondaryColor, // Use the secondaryColor property
    ),
  ),
);

Container(
  decoration: BoxDecoration(
    gradient: AppColor.linearGradient, // Use the linearGradient property
  ),
  child: Text(
    'Hello World',
    style: TextStyle(
      color: AppColor.accentColor, // Use the accentColor property
    ),
  ),
);

..

Properties:

  • AppColor: Class to hold all colors used in the app.
  • primaryColor: A static const property that stores a primary color.
  • secondaryColor: A static const property that stores a secondary color.
  • accentColor: An accent color used in the app.
  • linearGradient: A static const property that stores a linear gradient.
  • radialGradient: A radial gradient used in the app.
..


Comments