I want to change the color of a text widget based on a condition. If the variable isDark
is true, change color to black, else change color to white.
Using the code:
ListWidget(BuildContext context) => listItems
.map(
(e) => Center(
child: Text(
e,
style: const TextStyle(
fontSize: 20,
// The statement below highlights an "invalid constant" error on isDark
color: isDark ? Colors.black : Colors.white,
fontWeight: FontWeight.bold),
),
),
)
.toList();
How can I work around it or is there a better approach to doing it?
I also tried creating a const
variable like so:
if (!theme.darkMode)
const color = Colors.white;
else
const color = Colors.black;
but color still returns as an invalid constant.
2
Answers
In Dart, const variables are required to have constant values known at compile time. However, you are trying to conditionally set the value of color based on the isDark variable, which is not a constant. This is why you’re encountering the "invalid constant" error.
To achieve the desired behavior of changing the text color based on a condition, you can use a Builder widget inside your Text widget. The Builder widget will allow you to access the BuildContext of the widget and use it to apply the correct text color based on your condition.
In this example, the Builder widget provides the context needed to access the isDark variable, allowing you to conditionally set the text color. This approach ensures that the color value is not treated as a constant and works properly.
Your approach is okay. Just remove the
const
keyword fromTextStyle
.