Sharedpreferencs with flutter to save color

Viewed 1941

I want a container to be of a color, that comes from sharedpreference or something like that! Is there a widget to solve this!! Or can I just do this with sharedpreference!! If I can! How?

2 Answers

A better way is to save the color.value.

Use

final prefs = await SharedPreferences.getInstance();
Color myColor = Color(prefs.getInt('color') ?? Colors.blue.value);
// change Colors.blue to a default color

to get the color, and

prefs.setInt('color', myColor.value);

to save a color.

With flutter SharedPreferences plugin you can only save String, int, StringList, double, Bool.

A work around would be to save the RGBO value of the color in SharedPreferences, this would work for Android and iOS.

Step 1. Install the plugin

pubspec.yaml

Add SharedPreferences to your pubspec.yaml file. Check the last version by clicking here.

dependencies:
  flutter:
    sdk: flutter

  shared_preferences: ^0.5.3+4

Step 2. Save the RGBO value in SharedPreferences

  void saveColor(int r, int g, int b, double opacity) async {
    final prefs = await SharedPreferences.getInstance();
    prefs.setInt('r', r);
    prefs.setInt('g', g);
    prefs.setInt('b', b);
    prefs.setDouble('o', opacity);
  }

Step 3. Retrieve the value and create your color

getColor() async {
    final prefs = await SharedPreferences.getInstance();
    final r = prefs.getInt('r');
    final g = prefs.getInt('g');
    final b = prefs.getInt('b');
    final opacity = prefs.getDouble('o');
    return Color.fromRGBO(r, g, b, opacity);
  }
Related