I have a Flutter app that loads a color hex code in a string from the shared preferences. I need to convert the hex code to a MaterialColor, which can be applied to the primarySwatch in the Scaffold widget. Is there a way I can do it?
CodePudding user response:
You can try this:
save you color like this as String
:
final prefs = await SharedPreferences.getInstance();
await prefs.reload();
prefs.setString('color', '0xff3B68FF');
and then read it like this:
final prefs = await SharedPreferences.getInstance();
await prefs.reload();
String? obj = prefs.getString('color');
if (obj != null) {
setState(() {
colors = obj;
});
}
then use it like this:
Theme(
data: ThemeData(
primarySwatch: MaterialColor(
int.parse(colors),
<int, Color>{
50: Color(int.parse(colors)),
100: Color(int.parse(colors)),
200: Color(int.parse(colors)),
300: Color(int.parse(colors)),
400: Color(int.parse(colors)),
500: Color(int.parse(colors)),
600: Color(int.parse(colors)),
700: Color(int.parse(colors)),
800: Color(int.parse(colors)),
900: Color(int.parse(colors)),
},
)),
child: Row(),
)