Search code examples
flutterdartsharedpreferences

how to save color in sharedpreferences


i am trying to save Color in sharedpreference but it has only limited data type (String, int, double etc) i dont know

Future getColor() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    Color color = prefs.getString("color"); //error 
    return color;
  }

  Future setColor(Color themeColor) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString("color", (themeColor); //error
  }

}


Solution

  • I hope this code helps you. It can be written in a more beautiful way but I hope you get the idea.

    //Convert the color to hex, Save it in preferences
    var myColor = Colors.blue;
    var hex = '#${myColor.value.toRadixString(16)}';
    //save Hex value in sharedpreference.
    
    //get the hex value from shared preferences and convert it into color.
    Color yourColor= hexToColor(colorStringFromSharedPreference);
    
    Color hexToColor(String code) {
      return Color(int.parse(code.substring(1, 7), radix: 16) + 0xFF000000);
    }
    
    

    Also as suggested in the comment, you can also store the int value of the color.

    
    int myColorInteger = myColor.value
    //store integer value in sharedpreference
    

    and retrieving it and using Color's constructor

    //retrieve intValue of color from sharedpreference and
    Color myColor = Color(intValue)