Skip to content

Instantly share code, notes, and snippets.

@CassiusPacheco
Created February 12, 2021 01:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CassiusPacheco/41483e3dc18b5e735094cf942d3c257c to your computer and use it in GitHub Desktop.
Save CassiusPacheco/41483e3dc18b5e735094cf942d3c257c to your computer and use it in GitHub Desktop.
[Dart/Flutter] Color to Material Color
import 'package:flutter/material.dart';
extension MaterialX on Color {
MaterialColor toMaterial() {
return _createMaterialColor(this);
}
// Taken from https://medium.com/@filipvk/creating-a-custom-color-swatch-in-flutter-554bcdcb27f3
MaterialColor _createMaterialColor(Color color) {
final List<double> strengths = [.05];
final Map<int, Color> swatch = {};
final int r = color.red, g = color.green, b = color.blue;
for (int i = 1; i < 10; i++) {
strengths.add(0.1 * i);
}
for (final strength in strengths) {
final double ds = 0.5 - strength;
swatch[(strength * 1000).round()] = Color.fromRGBO(
r + ((ds < 0 ? r : (255 - r)) * ds).round(),
g + ((ds < 0 ? g : (255 - g)) * ds).round(),
b + ((ds < 0 ? b : (255 - b)) * ds).round(),
1,
);
}
return MaterialColor(color.value, swatch);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment