如何在共享首选项中保存颜色
how to save color in sharedpreferences
我正在尝试将 Color 保存在 sharedpreference 中,但它只有有限的数据类型(String、int、double 等)我不知道
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
}
}
希望这段代码对您有所帮助。它可以写得更漂亮,但我希望你能理解。
//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值。
int myColorInteger = myColor.value
//store integer value in sharedpreference
并检索它并使用 Color 的构造函数
//retrieve intValue of color from sharedpreference and
Color myColor = Color(intValue)
我正在尝试将 Color 保存在 sharedpreference 中,但它只有有限的数据类型(String、int、double 等)我不知道
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
}
}
希望这段代码对您有所帮助。它可以写得更漂亮,但我希望你能理解。
//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值。
int myColorInteger = myColor.value
//store integer value in sharedpreference
并检索它并使用 Color 的构造函数
//retrieve intValue of color from sharedpreference and
Color myColor = Color(intValue)