Handling Flutter Colors like a Pro

Maruf Hassan
3 min readMay 30, 2021

--

This is Part #4 of the series in Flutter Production Level Development where I teach you all the tips and tricks used in an Industry Level Production app.

If you prefer videos over articles then you can watch the companion 1 min #Short video on this article.

When building a production-ready app, the most requested change by the Client is to change various colors in the app. After some time it can become very hectic. To solve this we store all our Colors in one place. This helps in making changes and debugging a lot easier and faster.

This is how people normally use Color in general.

While there is nothing wrong with the above method, there are some disadvantages of using this way -

  1. Debugging becomes difficult while you have to scavenge through different files to find which color change is required.
  2. Bugfixes require multiple commits in different files becoming more prone to merge conflicts.

To fix this we create a class that holds all the Colors that our app will contain.

Create a dart file called colors.dart in the constants folder.

The file will contain a class with a private constructor and Colors used in our app.

import 'package:flutter/widgets.dart';class AppColor {
AppColor._();
static const Color blueColor = Color(0xFF2F39C5);
static const Gradient linearGradient = LinearGradient(
begin: Alignment(0.0, 0.0),
end: Alignment(0.707, -0.707),
colors: [
Color(0xffff9a9e),
Color(0xfffad0c4),
Color(0xfffad0c4),
],
);
}

AppColor is the class name.

AppColor._(); is a private constructor which prevents the class from being instantiated.

static means a member is available on the class itself instead of on instances of the class.

const makes the variable immutable.

blueColor is the Color name.

Color(0xFF2F39C5) is the color in hex code.

We can also store Gradient colors in this class.

Now that we understand what everything does, we will apply it to our code.

Replace the floating Color with AppColor.blueColor.

You can do the same for Gradient colors as well.

Advantages of using this way -

  1. Debugging becomes a breeze since all the Colors are in one file and changing any Color is very easy.
  2. Bugfixes require a single commit as all the Colors are available in a single file, thus reducing the chances of merge conflicts.

I hope you liked the article. I plan on bringing more short articles like these to teach tips and tricks used in Production Level Flutter Development!

You can read about Handling Flutter Images like a Pro in Part #3 of the series.

You can follow me on Twitter, Github, or Youtube to stay updated with all my new articles and videos.

--

--

No responses yet