import 'package:flutter/material.dart';
class colors {
static Color bgColor = Color(0xfff8f8f8);
}
And I wish to change its value when I press on a button
I imported the dart file in my new file and iniside the onpressed function of my button I have:
MaterialApp(
home: Scaffold(
backgroundColor: colors.bgColor,
...
onPressed: () {
setState(() {
colors.bgColor = Color(0xff313131);
});
},
The color inside of bgColor.dart does show up but when I try to change it onPressed (also in an stateful widget) it does not change the scaffold color
First of all make sure that backgroundColor: colors.bgColor
and setState
both are in the same stateful widget, it should work(tested)
this way is not dependent on setState
so you can use it in both stateless and stateful widgets
ValueNotifier<Color>
,optional: name types using UpperCamelCase
class CustomColors {
static ValueNotifier<Color> bgColor = ValueNotifier(const Color(0xfff8f8f8));
}
ValueListenableBuilder
and access color with value
property MaterialApp(
home: ValueListenableBuilder<Color>(
valueListenable: CustomColors.bgColor,
builder: (context, value, child) => Scaffold(
backgroundColor: value,
onPressed: () {
CustomColors.bgColor.value = Colors.red;
}