Flutter - Color name string to material color

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.


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.

Tags:

Flutter