Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - Color name string to material color

Tags:

flutter

In Flutter is there a way to generate a material color from it's name, without creating a full map Map<String,MaterialColor>.

In theory, something like this:

String colorName = "deepOrange";
MaterialColor color = Colors(colorName);
like image 778
Zvi Karp Avatar asked Mar 06 '19 16:03

Zvi Karp


2 Answers

According to the comment, the intention is to save and read back from shared_preferences. In that case, it is better to save and retrieve the color by int value, not by string name, to ensure we always get the color.

  • Save: prefs.setInt("prefered_color", Color.value)
  • Retrieve: Color c = const Color(prefs.getInt('prefered_color') ?? 0xFF42A5F5);

According to the official doc, there's currently no API to perform the function you described. Although it's easy to implement your methodology, I doubt its usefulness in general cases. Also we have to deal with typos or noSuchColor errors. But using const / enum will offer the advantage of compile time error checking.

like image 135
TruongSinh Avatar answered Oct 05 '22 07:10

TruongSinh


I manage to do something like that using the Colors.primaries list ( found in the colors.dart file):

    //colors.dart

    /// The material design primary color swatches, excluding grey.
    static const List<MaterialColor> primaries = <MaterialColor>[
      red,
      pink,
      purple,
      deepPurple,
      indigo,
      blue,
      lightBlue,
      cyan,
      teal,
      green,
      lightGreen,
      lime,
      yellow,
      amber,
      orange,
      deepOrange,
      brown,
      // The grey swatch is intentionally omitted because when picking a color
      // randomly from this list to colorize an application, picking grey suddenly
      // makes the app look disabled.
      blueGrey,
    ];

So in order to save the colors:

    Color colorToSave = Colors.indigo;
    prefs.setInt("colorIndex", Colors.primaries.indexOf(colorToSave));

To retrieve:

    MaterialColor colorSaved = Colors.primaries(getInt('colorIndex') ?? 0);

Hope that helps you.

like image 31
carles.sole.grau Avatar answered Oct 05 '22 07:10

carles.sole.grau