Reputation: 567
I try to change background colors all pages in app. User can select color from a pallete in SettingsPage.
Wrap(
children: List<Widget>.generate(
mainColor.length,
(index) => GestureDetector(
onTap: () {
setState(() {
_selectedColor = index;
box.write('_selectedColor', index);
box.write(
'color0',
mainColor[index]
.toString()
.split('(')[1]
.split(')')[0]);
});
},
child: Padding(
padding: const EdgeInsets.all(4),
child: Container(
width: 30,
height: 30,
decoration: BoxDecoration(
border: Border.all(color: Colors.grey, width: 2),
shape: BoxShape.circle,
),
child: CircleAvatar(
// ignore: sort_child_properties_last
child: _selectedColor == index
? const Icon(Icons.done,
size: 16, color: Colors.white)
: null,
backgroundColor: mainColor[index],
radius: 14,
),
),
),
),
),
),
I have list of background colors.
List<Color> mainColor = [
const Color(0xffEF5350),
const Color(0xffF44336),
const Color(0xffBDBDBD),
const Color(0xff9E9E9E),
const Color(0xffEC407A),
const Color(0xffE91E63),
];
I read color in other pages like below
backgroundColor: Color(int.parse(box.read('color0'))),
My problem is when i navigate back to previous page, color changes not apply. If i start app again, color changes applied.
Upvotes: 0
Views: 165
Reputation: 17890
The reason this is not working is that your previous pages doesn't notify when ever the background color changes. First define new class like this and call it CustomBackground
:
class CustomBackground with ChangeNotifier {
Color _backgroundColor = Colors.white;
Color get backgroundColor => _backgroundColor;
Future<void> changeBackgroundColor(Color color, GetStorage box) async {
_backgroundColor = color;
box.write('color0', color.toString()
.split('(')[1]
.split(')')[0]);
notifyListeners();
}
}
then use it like this in your app:
Scaffold(
backgroundColor: Provider.of<CustomBackground>(context, listen: false).backgroundColor,
...
)
also don't forget to wrap your main MaterialApp
with ChangeNotifierProvider
in order to access your CustomBackground
in every page of your app:
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider<CustomBackground>(
create: (_) => CustomBackground(),
child: Consumer<CustomBackground>(
builder: (context, backgroundColor, _) {
return MaterialApp(
...
},
);
},
),
);
}
and finally change your onTap
to this:
onTap: () {
setState(() {
_selectedColor = index;
box.write('_selectedColor', index);
Provider.of<CustomBackground>(context, listen: false).changeBackgroundColor(mainColor[index], box);
});
},
Upvotes: 2