如何在共享首选项中保存颜色 [英] how to save color in sharedpreferences
本文介绍了如何在共享首选项中保存颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将Color保存在sharedpreference中,但是它只有有限的数据类型(字符串,int,double等),我不知道
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
}
}
推荐答案
我希望这段代码对您有所帮助.可以用更漂亮的方式编写它,但希望您能理解.
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);
}
此外,如注释中所建议,您还可以存储颜色的int值.
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
并使用Color的构造函数进行检索
and retrieving it and using Color's constructor
//retrieve intValue of color from sharedpreference and
Color myColor = Color(intValue)
这篇关于如何在共享首选项中保存颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文